更新JSON对象列表中的JSON对象
所以我在看一个关于更新JSON对象列表的视频。在1:23,在更新JSON对象列表中的JSON对象,json,reactjs,Json,Reactjs,所以我在看一个关于更新JSON对象列表的视频。在1:23,在updateTodo()方法中,我注意到他使用.find()从JSON列表中更新JSON对象的方式。直接使用,todo.name=data.name编辑它,然后setState({todos:todos}) 有人能解释一下吗?当满足某些条件时,您不需要遍历JSON对象列表而替换特定的JSON对象吗?我不明白他为什么不循环遍历todos列表来替换该值。有人能给我解释一下原因吗 代码片段: updateTodo(data) {
updateTodo()
方法中,我注意到他使用.find()
从JSON列表中更新JSON对象的方式。直接使用,todo.name=data.name
编辑它,然后setState({todos:todos})
有人能解释一下吗?当满足某些条件时,您不需要遍历JSON对象列表而替换特定的JSON对象吗?我不明白他为什么不循环遍历todos列表来替换该值。有人能给我解释一下原因吗
代码片段:
updateTodo(data) {
axios.put('/api/todo/update/' + data.id, data)
.then(response => {
let todos = [...this.state.todos];
let todo = todos.find(todo => {
return todo.id === data.id;
});
todo.name = data.name;
this.setState({
todos: todos,
});
}).catch(error => {
console.error(error);
});
}
任何见解都值得赞赏。感谢阅读。在React中,您不能直接更新状态。这样做
let todos = [...this.state.todos];
它创建处于状态的todos
属性的副本,并且不引用处于状态的值
让todoId=2;
让todos=[
{id:1,名称:“todo 1”,完成:false},
{id:2,名称:“todo 1”,完成:false},
{id:3,名称:“todo 1”,完成:false}
]
让todo=todos.find((todo)=>todo.id==todoId);
//如果我更新前一个toto变量的任何属性,它也会更新`todos'中的值`
todo.name=“更新的todo名称”;
控制台日志(todos)
在数组中循环,直到找到合适的元素,或者如果找不到,则退出undefined
。