为了练习 Redux,我在 index.js 中
const state = [
{
resort: 'Jay Peak',
date: '2018-2-22',
powder: true,
backcountry: false,
},
];
const action = {
type: constants.ADD_DAY,
payload: {
resort: 'Mad River Glen',
date: '2018-3-14',
powder: true,
backcountry: false,
},
};
const nextState = allSkiDays(state, action);
console.log(`
initial state: ${JSON.stringify(state)}
action: ${JSON.stringify(action)}
new state: ${JSON.stringify(nextState)}
`);
以及我的合成 reducer ,
export const skiDay = (state = [], action) => {
action.type === constants.ADD_DAY ? action.payload : state;
};
export const allSkiDays = (state = [], action) => {
switch (action.type) {
case constants.ADD_DAY:
return [...state, skiDay(null, action)]; // COMPOSITION!!!! use skiDay()
default:
return state;
}
};
我不断得到这个结果,
initial state: [{"resort":"Jay Peak","date":"2018-2-22","powder":true,"backcountry":false}]
action: {"type":"ADD_DAY","payload":{"resort":"Mad River Glen","date":"2018-3-14","powder":true,"backcountry":false}}
new state: [{"resort":"Jay Peak","date":"2018-2-22","powder":true,"backcountry":false},null]
我已经尝试了很多方法,为什么 null 仍然被传播到数组而不是新对象上?
最佳答案
此 reducer 不会返回下一个状态。
export const skiDay = (state = [], action) => {
action.type === constants.ADD_DAY ? action.payload : state;
};
这样做:
export const skiDay = (state = [], action) => {
return action.type === constants.ADD_DAY ? action.payload : state;
};
关于javascript - Reducer 没有将对象添加到数组中,而是添加了 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51752995/