如何使用对象数组中的状态更新状态? [英] How to update state with usestate in an array of objects?

查看:0
本文介绍了如何使用对象数组中的状态更新状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Reaction useState挂钩时遇到一些问题。我有一个带有复选框按钮的Todolist,我想将‘Done’属性更新为‘True’,该属性的id与‘Click’复选框按钮的id相同。如果我sole.log我的‘toggleDone’函数,它会返回正确的id。但我不知道如何才能更新正确的属性。

当前状态:

const App = () => {

  const [state, setState] = useState({
    todos: 
    [
        {
          id: 1,
          title: 'take out trash',
          done: false
        },
        {
          id: 2,
          title: 'wife to dinner',
          done: false
        },
        {
          id: 3,
          title: 'make react app',
          done: false
        },
    ]
  })

  const toggleDone = (id) => {
    console.log(id);
}

  return (
    <div className="App">
        <Todos todos={state.todos} toggleDone={toggleDone}/>
    </div>
  );
}

我想要的更新状态:

const App = () => {

  const [state, setState] = useState({
    todos: 
    [
        {
          id: 1,
          title: 'take out trash',
          done: false
        },
        {
          id: 2,
          title: 'wife to dinner',
          done: false
        },
        {
          id: 3,
          title: 'make react app',
          done: true // if I checked this checkbox.
        },
    ]
  })

推荐答案

您可以安全地使用Java脚本的数组映射功能,因为这不会修改现有的状态,这是Reaction不喜欢的,并且它会返回一个新的数组。该过程是遍历状态数组并找到正确的id。更新done布尔值。然后使用更新后的列表设置状态。

const toggleDone = (id) => {
  console.log(id);

  // loop over the todos list and find the provided id.
  let updatedList = state.todos.map(item => 
    {
      if (item.id == id){
        return {...item, done: !item.done}; //gets everything that was already in item, and updates "done"
      }
      return item; // else return unmodified item 
    });

  setState({todos: updatedList}); // set state to new object with updated list
}

编辑:已更新代码以切换item.done,而不是将其设置为True。

这篇关于如何使用对象数组中的状态更新状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆