我正在使用 react redux 开发一个待办事项应用程序,它的初始状态是一个对象initialState
,并且有一个数组 task
,它是一个空数组。在设置 的值时task
,我似乎无法找到一种方法来获取对象的当前索引以将其分配给id
。我尝试过使用indexOf()
and thefindIndex()
但还没有找到最好的方法来处理它。我希望 id 等于其对象的索引。(如果对象在任务数组中的索引 0 处,则该 id 等于 0)并且在数组更改或具有多个对象时也可以工作。感谢您的帮助,谢谢
这是我的初始状态
export const initialState = {
task: []
}
这是我的减速机
const manageTodoReducer = (state, action) => {
switch(action.type) {
case "ADD_TODO":
return (
{
...state,
task: [
...state.task,
{
name: "This is the name",
id: state.task.findIndex(x => x.name === state.task.name),
complete: false
}]
}
)
default:
return state
}
}