1、
在src文件夹下创建:store文件=》configureStore.js,用来放置redux的启动代码。只要是返回一个store.
//整体的代码骨架:
import {
createStore,
applyMiddleware,
combineReducers
} from 'redux'
import thunk from 'redux-thunk'
// 引入reducer
import reducers from './reducers'
const rootReducers = combineReducers({
...reducers
})
const middleweares = applyMiddleware(thunk)
function configureStore(){
return createStore(rootReducers,middleweares)
}
export default configureStore
2、拆分reducer到对应文件,不要都写在index.js
如:counterRedux.js下放置对应的reducer和action,导出reducer
注意:不要把所有action都放在同一文件下,将对应的action放置在对应的redux文件下,把所有的action都使用export导出去。
const INCREASE = 'INCREASE/rdx/magicNum'
const DECREASE = 'DECREASE/rdx/magicNum'
// 把所有的action放到一个对象中,最后需要导出这个对象
let actions = {
increaseAction : (val)=>({
type: INCREASE,
val
}),
decreaseAction : (val)=>(dispatch,getState)=>{
if(getState()-val >= 0){
dispatch({
type: DECREASE,
val
})
}
},
increaseByOddAction : (val)=>(dispatch,getState)=>{
if(getState()%2!==0){
dispatch(increaseAction(val))
}
},
increaseByAsyncAction : (val)=>(dispatch,getState)=>{
setTimeout(()=>{
dispatch(decreaseAction(val))
},1000)
}
}
export {actions}
export default function counter(state=0,action){
let {type,val} = action
switch (type) {
case INCREASE :
return state+val
break;
case DECREASE :
return state-val
break;
default :
return state
}
return state
}
3、组合reducers
引入需要的reducer
import counter from '../component/counterRedux'
import magicNum from '../component/magicNumRedux'
export default {
counter,
magicNum
}

网友评论