我正在使用简单的年龄递增和递减示例来学习redux,这里的代码是
const { createStore } = require(`redux`);
const initialState = {age: 21};
const reducerOne = (state = initialState, action) => {
const newState = {...state};
if(action.type === `ADD`) {
newState.age = action.value;
}
if(action.type === `SUBTRACT`) {
newState.age = action.value;
}
return newState;
}
const store = createStore(reducerOne);
store.subscribe(() => {
console.log(`State Changed` + JSON.stringify(store.getState()));
})
store.dispatch({type: `ADD`, val: 10});
store.dispatch({type: `SUBTRACT`, val: 5});
但是在Output中,它显示如下-> State Changed {} 帮助解决此问题并获取输出
答案 0 :(得分:1)
您的操作正在发布val
属性,而减速器正在读取value
属性。
以这种方式更改操作,它将起作用:
store.dispatch({type: `ADD`, value: 10});
store.dispatch({type: `SUBTRACT`, value: 5});
编辑:
您要替换旧的age
值,但是可能要添加或减去它。您必须修改减速器才能实现这种行为:
const reducerOne = (state = initialState, action) => {
const newState = {...state};
if(action.type === `ADD`) {
// add to the previous `age` value and do not overwrite it
newState.age = state.age + action.value;
}
if(action.type === `SUBTRACT`) {
// subtract from the previous `age` value and do not overwrite it
newState.age = state.age - action.value;
}
return newState;
}