And*_*cik 5 typescript reactjs redux react-redux
我认为Redux具有很大的价值,但是对我来说,主要问题在于当今的reducer的编写方式:
const addToDoReducer = (state, action) => {
switch (action.type) {
case ADD_TODO:
return Object.assign({}, state, {
todos: todos(state.todos, action)
})
case TOGGLE_TODO:
return Object.assign({}, state, {
todos: todos(state.todos, action)
})
default:
return state
}
}
Run Code Online (Sandbox Code Playgroud)
...最终,减速器成为项目的薄弱环节
问:有没有更好的方法/选项来编写reducer:
像这样:
const addToDoReducer = (state:toDoState, action:addAction) =>
{
return { ...state, toDos: [...state.toDos, action.toDoObject] };
}
Run Code Online (Sandbox Code Playgroud)
还是已经有这样做的图书馆?
您可以创建这样的模块:
// createReducer.js
export default (initiateState, reducerMap) => {
return function(state, action) {
const currentState = state !== undefined ? state : initiateState;
const handler = reducerMap[action.type];
return handler ? handler(currentState, action) : currentState;
};
};
Run Code Online (Sandbox Code Playgroud)
然后,在第一个参数中设置初始状态并将操作列表存储为对象。例如:
import createReducer from './createReducer';
const STORE_TEST_MODULE = 'STORE_TEST_MODULE';
export default createReducer(
// Initial state
{
test: null,
},
{
// Custom action #1
[STORE_TEST_MODULE]: (state, action) => {
return {...state, ...action.payload};
},
// Custom action #2
'CLEAR_TEST': (state, action) => {
return {test: null};
},
}
);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
784 次 |
最近记录: |