Redux reducer 是 Redux 状态管理库中的一个纯函数,它接收当前状态和一个动作(action),然后返回一个新的状态。如果你发现 reducer 没有设置正确的状态,可能是以下几个原因:
const initialState = { count: 0 };
const store = createStore(reducer, initialState);
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
}
type
属性,并且其他必要的数据也正确无误。function increment() {
return { type: 'INCREMENT' };
}
function decrement() {
return { type: 'DECREMENT' };
}
store.getState()
来获取状态,确保你在 action 被分发(dispatch)之后再获取状态。store.dispatch(increment());
console.log(store.getState()); // 应该显示 count 增加了
const store = createStore(reducer, initialState, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
function incrementAsync() {
return dispatch => {
setTimeout(() => {
dispatch(increment());
}, 1000);
};
}
如果你遵循了以上步骤,但 reducer 仍然没有设置正确的状态,可以尝试以下步骤来调试:
console.log
在 reducer 中打印当前状态和 action,以确保它们是你预期的值。mapStateToProps
来获取状态。参考链接:
如果你需要进一步的帮助,请提供更多的代码示例或错误信息,以便更准确地诊断问题。
领取专属 10元无门槛券
手把手带您无忧上云