【发布时间】:2018-03-12 22:50:24
【问题描述】:
我正在传递posts 数组中对象的索引(id),处于要更新的状态。我可以使用findIndex 找到元素的索引并更改number 键。我不知道如何将更新后的object 传递回状态/数组。
我的减速机:
const initialState = {
posts: [
{id:1, name:'post1', number:11},
{id:2, name:'post2', number:22},
{id:3, name:'post3', number:33}
]
}
export default function newData (state = initialState, action) {
switch (action.type) {
case "updateNumber": {
// find object to update
const index = state.posts.findIndex(({ id }) => id === action.payload);
if (index > -1 ) {
const toIncrement = state.posts[index];
const number = toIncrement.number++;
// create new object with existing data and newly incremented number
const updatedData = { ...toIncrement, number };
// return new array that replaces old object with incremented object at index
// the state is not getting updated with the following:
return [...state.posts.slice(0, index), updatedData, ...state.posts.slice(index + 1)];
}
// return state if no object is found
return state;
}
default:
return state
}
}
我做错了什么?还有其他方法可以更新状态吗?请帮忙。
【问题讨论】:
-
我认为您正在改变
redux中不允许的state尝试将这一行const toIncrement = state[index];更改为这一行:const toIncrement = {...state[index]}; -
对不起,我用
initialState更新了问题。我做了const toIncrement = {...state.posts[index]};,到目前为止一切都很好。但是状态没有更新。
标签: reactjs react-native ecmascript-6 redux react-redux