Reactjs 错误反应Redux工具包:为什么我可以';t使用.findIndex更改数组对象的键值

Reactjs 错误反应Redux工具包:为什么我可以';t使用.findIndex更改数组对象的键值,reactjs,redux,redux-toolkit,Reactjs,Redux,Redux Toolkit,我正在使用React Redux工具包创建一个简单的todo应用程序。如果用户单击复选框,它将更改.isComplete的键值。我使用.findIndex来查找特定任务的索引。但问题是我无法更改数组的第一个对象的键值,而其他对象的键值工作正常 const initialState = [ { _id: uuidv4(), title: 'Learn React', desc: 'Nec ullamcorper sit amet risus nullam eget fe

我正在使用React Redux工具包创建一个简单的todo应用程序。如果用户单击复选框,它将更改.isComplete的键值。我使用.findIndex来查找特定任务的索引。但问题是我无法更改数组的第一个对象的键值,而其他对象的键值工作正常

const initialState = [
  {
    _id: uuidv4(),
    title: 'Learn React',
    desc: 'Nec ullamcorper sit amet risus nullam eget felis.',
    isComplete: false,
    priority: 'Minor',
    created: 'johndoe',
    assigned: 'J Doe',
    dateCreated: new Date(),
    dateDue: new Date(),
  },
  {
    _id: uuidv4(),
    title: 'Learn Node JS',
    desc:
      'Risus nec feugiat in fermentum posuere urna. Est ante in nibh mauris cursus mattis molestie a. Malesuada pellentesque elit eget gravida cum.\n\nUt lectus arcu bibendum at varius vel pharetra vel.\n\nFacilisis magna etiam tempor orci eu lobortis elementum nibh tellus. Rutrum tellus pellentesque eu tincidunt tortor. Imperdiet nulla malesuada pellentesque elit eget gravida cum sociis natoque.',
    isComplete: false,
    priority: 'High',
    created: 'johndoe',
    assigned: 'J Doe',
    dateCreated: new Date(),
    dateDue: new Date(),
  },  
];

JS
export const taskSlice = createSlice({
  name: 'tasks',
  initialState: initialState,
  reducers: {
    completeTodo: (state, action) => {
      const taskIndex = state.findIndex((e) => e._id === action.payload);
      if (taskIndex) {
        state[taskIndex].isComplete = true;
      }
    },
  },
});

通常,如果未找到任何内容,则
findIndex
-1
,对于第一项为
0
。如果,您的
将跳过它,因为它是一个假值

可能是正确的

const taskIndex=state.findIndex((e)=>e._id==action.payload);
如果(任务索引!=-1){
状态[taskIndex].isComplete=true;
}
但你也可以这样做

const task=state.find((e)=>e._id==action.payload);
如果(任务){
task.isComplete=true;
}

我忘记了.findIndex的返回值。我很笨,哈哈。.find是我计划的原始解决方案,我只想探索.findIndex。先生,非常感谢您对我的帮助!!!