如何更新一个对象数组的状态?

时间:2018-12-08 04:47:50

标签: reactjs

我的状态如下

this.state = {
            todos: [{
                title: 'asas',
                status: 'incomplete',
                uuid: 11
            }, {
                title: 'asas',
                status: 'incomplete',
                uuid: 12

            }, {
                title: 'asas',
                status: 'complete',
                uuid: 13

            }],

            currentTab: "Show All"
        }

每当用户单击待办事项的任何复选框时,我都想更新该复选框的状态,并且我已经为其编写了以下代码

 this.state.todos.map(todo => {
            if (todo.uuid === uuid) todo.status = (todo.status === 'complete') ? 'incomplete' : 'complete'
        });
        this.forceUpdate();

在这里使用forceUpdate是个好方法吗?因为我只更新了对象数组中的单个值。对于这个问题有更好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

以下任何一种都会在不修改当前状态的情况下调用具有更新状态的setState。

https://redux.js.org/recipes/structuringreducers/immutableupdatepatterns#inserting-and-removing-items-in-arrays

使用点差运算符:

编辑..实际上,这是困难的方法8) 参见https://redux.js.org/recipes/structuringreducers/immutableupdatepatterns#updating-an-item-in-an-array

this.setState(prevState => {
  const idx = prevState.todos.findIndex(todo => todo.uuid === uuid);
  return {
    todos: [
      ...prevState.todos.slice(0, idx),
      {
        ...prevState.todos[idx],
        status: prevState.todos[idx].status === "complete" ? "incomplete" : "complete",
      }
      ...prevState.todos.slice(idx + 1),
    ]
  }
});

或使用沉浸式:

import produce from "immer";

this.setState(prevState => {
  const idx = prevState.todos.findIndex(todo => todo.uuid === uuid);
  return produce(prevState, draft => {
    draft.todos[idx].status = prevState.todos[idx].status === "complete" ? "incomplete" : "complete"
  });
});