更新您的状态,不要使用push
。使用concat
我面对这真是奇怪的问题,考虑这个减速机:
export default function(state = null, action) {
console.log("Current State: ",state);
// on performing actions, it gives me:
// Current State: null
// Current State: Array [{}]
// Current State: Array [{}] -- all good
if(state === null) {
state = [
{id: 1, title: "Java"}
];
}
// UPDATED PART. FORGOT TO MENTION IT BEFORE
if(Action.type == "UPDATE_LIST") {
state.push( Action.payload ); // don't do that, this'll mutate your array and states are immutable
}
/////////////
return state; // this is the main problem
}
上面的代码没有我的组件内部调用mapStateToProps
。然而,修改上述减速器等向下下面的确激活mapStateToProps
:
return []; // instead of return state;
要么
return [ {id: 1, title: "Python"} ]; // instead of return state;
我回国的instanceof阵在两种情况下[状态&[],但只有后者是在我的组件调用mapStateToProps
。
这就奇怪了,我已经不知道什么是我该做的,解决这个问题。
终极版的一点是要确保你的状态是不能直接可变的。由于数组和对象是通过在Javascript中引用传递,你的代码试图变异的状态对象directly..which不正确。
总是返回新的状态发生变异的状态。像这样:
export default function(state = null, action) {
let newState = [...state];
if(state === null) {
newstate = [
{id: 1, title: "Java"}
];
}
return newState;
}
不喜欢这种方式:
if(state === null) {
state = [
{id: 1, title: "Java"}
];
return state;
}
return state;