state.findIndex 不是 findIndex 的函数错误



我正在将对象的id作为action.payload传递给化简器以修改对象。

还原剂:

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数组中找到元素的索引?控制台.log操作使我{type: "updateNumber", payload: 2}payload是按下的元素。

UPDATE1:

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
}
}

所以这应该返回该州更新numberposts,对吧?

你的initialState是一个object

我想你的意思是

state.posts.findIndex(({ id }) => id == action.payload);  

或者可以将initialState更改为

const initialState = [
{id:1, name:'post1', number:11},
{id:2, name:'post2', number:22},
{id:3, name:'post3', number:33}
]

编辑作为您编辑
的后续,在您更改后,
现在您可以执行以下操作:

const number = toIncrement.number++;

totalIncrement将保存这样的对象,例如:

{id:1, name:'post1', number:11}  

编辑#2我认为
您正在更改redux中不允许的state.
尝试更改以下内容:

if (index > -1 ) {
const toIncrement = state.posts[index];
const number = toIncrement.posts.number++;  

对此:

if (index > -1 ) {
const toIncrement = {...state.posts[index]};
const number = toIncrement.posts.number + 1; // i hope this is a number and not a string!

另一件事,你的初始状态是一个对象,但你的化简器返回一个数组。
更改此行:

// 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 new array that replaces old object with incremented object at index
return { posts: [...state.posts.slice(0, index), updatedData, ...state.posts.slice(index + 1)]};

相关内容

  • 没有找到相关文章

最新更新