3 回答
![?](http://img1.sycdn.imooc.com/54584e120001811202200220-100-100.jpg)
TA贡献1829条经验 获得超7个赞
push
返回新length
的 mutated array
。使用concat
,而不是返回一个新的数组
results : state.results.concat(item)
让我们假设以下代码
results : state.results.push('foo')
假设 results
有一个length
of 5
,上面的代码将断言
results : 5
下次您尝试push
results
这样做时,您的编译器会是什么样子
5.push('foo')
![?](http://img1.sycdn.imooc.com/533e4cde000148e602000200-100-100.jpg)
TA贡献1895条经验 获得超7个赞
返回值的.push就是
调用方法的对象的新长度属性。
添加值以stae.results使用concat或spread 语法:
case "STORE_RESULT": {
return {
...state,
results: [...state.results, state.counter]
};
}
![?](http://img1.sycdn.imooc.com/5458477300014deb02200220-100-100.jpg)
TA贡献1779条经验 获得超6个赞
您应该在减速器开关中添加默认情况。
并使用[...state.results, state.counter]代替state.results.push(state.counter)。
像这样
const intialState = {
counter: 0,
results: []
};
const reducer = (state = intialState, action) => {
switch (action.type) {
case "INCREMENT":
return {
...state,
counter: state.counter + 1
};
case "STORE_RESULT": {
return {
...state,
results: [...state.results, state.counter] // here
};
default:
return state; // here
}
}
};
export default reducer;
添加回答
举报