如何在 react.js 状态下改变数组内的对象?

时间:2021-06-03 08:42:47

标签: reactjs react-hooks react-component react-state

我在尝试更新状态时遇到问题。 这是我的代码:

const [todos, setTodos]= useState([])

useEffect(() => {
  setTodos([
{id:1, title: '', 
notes: [{id: 1, description: 'this is a simple description'}]}
])
}, [])

我的目标是向待办事项数组添加注释。 我试试这样

const i = todos.findIndex((t) => t.id === parseInt(id));
const newArr = todos[i].notes[0].push(note);
setTasks(newArr);

但它不起作用 newArr 给了我新状态的索引说明。 请帮忙 提前致谢

2 个答案:

答案 0 :(得分:1)

如果您想让它工作,您可以执行以下操作:

const newArr = todos[i].notes.push(note)

但这不是推荐的方式。

向 notes 数组添加新项目的最佳方法是使用 object.assign 或展开运算符,以免直接改变整个数组。像下面这样的东西:

const newArr = [...todos[i], note]

并使用这种方式来改变整个任务数组。

我认为 ar here 已经得到了很好的描述,如果您想了解更多关于为什么应该使用扩展运算符而不是推送的信息。

答案 1 :(得分:-1)

我创建了完美运行的 this。你需要做的是获取todo id并推送到它的笔记。此处 todo 状态已更新,但未调用渲染方法。为了调用 render 方法,我再次调用了 setTodo