React/Redux:状态调用了两次? (concat(),不是 push())
React/Redux: state called twice? (concat(), not push())
我在将新的 todo
添加到经典的 todos
时遇到问题。在 React/Redux.
上进行
这里是reducer-todos.js
:
export default function (state=[
{
id: 0,
todo: "Study English"
},
{
id: 1,
todo: "Run sprint"
},
{
id: 2,
todo: "Call Bob"
}], action) {
switch(action.type) {
case "ADD_TODO":
return state.push({id: state.length, todo: action.todo});
break;
}
return state;
}
这是我遇到的问题:
不知何故 todos
对象变成了 4
,而不是 Array[4]。为什么会这样?
如果需要更多信息,请告诉我。
Somehow todos object becomes 4, not Array[4]. Why is this happening?
您正在使用 push
,这将 return 其新尺寸。使用 concat
代替,这将 return 一个新数组,其中添加了你的新项目而不改变。
所以这个:
return state.push({id: state.length, todo: action.todo});
应该变成:
return state.concat({id: state.length, todo: action.todo});
我在将新的 todo
添加到经典的 todos
时遇到问题。在 React/Redux.
这里是reducer-todos.js
:
export default function (state=[
{
id: 0,
todo: "Study English"
},
{
id: 1,
todo: "Run sprint"
},
{
id: 2,
todo: "Call Bob"
}], action) {
switch(action.type) {
case "ADD_TODO":
return state.push({id: state.length, todo: action.todo});
break;
}
return state;
}
这是我遇到的问题:
不知何故 todos
对象变成了 4
,而不是 Array[4]。为什么会这样?
如果需要更多信息,请告诉我。
Somehow todos object becomes 4, not Array[4]. Why is this happening?
您正在使用 push
,这将 return 其新尺寸。使用 concat
代替,这将 return 一个新数组,其中添加了你的新项目而不改变。
所以这个:
return state.push({id: state.length, todo: action.todo});
应该变成:
return state.concat({id: state.length, todo: action.todo});