因为公司的redux结构不是太分明,因此研究了下redux的文件结构
- 首先我们对reducer功能进行分离,这样更利于后期维护。
// clearGoodsReducer.js
import constants from "../constants";
const { GOODS_CLEAR } = constants
export const clear = () => ({
type: GOODS_CLEAR
})
export const reducer = (state, action) => {
switch(action.type) {
case GOODS_CLEAR:
return {
...state,
goodsNameList: []
}
default:
return state
}
}
- 然后constants.js中统一存储状态值
export default {
GOODS_GET_SUCCESS: 'get_goods_success',
GOODS_GET_FAIL: 'get_goods_fail',
GOODS_GET_LOADING: 'get_goods_loading',
GOODS_CLEAR: 'clear_goods',
}
- actions.js中对方法进行统一存储
export { clear } from './components/clearGoodsReducer'
- 再在/goods/index.js中进行统一管理
import { reducer as getGoodsReducer } from "./components/getGoodsReducer";
import { reducer as clearGoodsReducer } from "./components/clearGoodsReducer";
const init = {
status: 'pendding',
goodsNameList: []
}
// 对reducer的方法进行存储 需要新增或删除只需在数组中进行修改就可以
const reducer = [
getGoodsReducer,
clearGoodsReducer
]
export default (state = init, action) => {
let newData = state
switch(action.type) {
default:
newData = state; break;
}
return reducer.reduce((s, r) => r(s, action), newData)
}
- 然后在store中按照正常流程引入reducers/NAME
import { createStore, compose, applyMiddleware } from "redux";
import thunkMiddleware from 'redux-thunk'
import reducers from "../reducers";
const middlewares = [thunkMiddleware]
const enhancer = compose(applyMiddleware(...middlewares))
const storeConfig = (preloadedState) => createStore(reducers, preloadedState, enhancer)
export default storeConfig
记录一下 方便下次记忆