【发布时间】:2017-10-01 07:51:25
【问题描述】:
我将对象的id 作为action.payload 传递给reducer 以修改对象。
减速机:
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.findIndex(({ id }) => id == action.payload);
if (index > -1 ) {
const toIncrement = state[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
return [...state.slice(0, index), updatedData, ...state.slice(index + 1)];
}
// return state if no object is found
return state;
}
default:
return state
}
}
但我收到错误消息:state.findIndex is not a function。如何找到posts数组中元素的索引? console.log 操作给了我{type: "updateNumber", payload: 2} 其中payload 是按下的元素。
更新1:
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.posts.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
return [...state.posts.slice(0, index), updatedData, ...state.posts.slice(index + 1)];
}
// return state if no object is found
return state;
}
default:
return state
}
}
所以这应该返回posts,并在状态中更新number,对吧?
【问题讨论】:
-
试试
state.posts.findIndex -
错误:
Cannot read property 'number' of undefined
标签: javascript reactjs react-native redux react-redux