React State 中更新对象和数组的速查表
如果我们想在 React 状态中使用数组或对象,则必须在修改值之前创建它的副本。这是一份速查表,介绍如何在管理 React 状态的上下文中对数组或对象中的项目进行添加、删除和更新。
数组
const [todos, setTodos] = useState([]);
添加到数组
const handleAdd = (todo) => {
const newTodos = todos.slice();
newTodos.push(todo);
setTodos(newTodos);
}
扩展运算符是用于创建引用的新副本的语法糖。
const handleAdd = (todo) => {
const newTodos = [...todos];
newTodos.push(todo);
setTodos(newTodos);
}
我们还可以使用扩展运算符来创建副本并附加一个项目,语法如下:
const handleAdd = (todo) => {
setTodos([...todos, todo]);
}
从数组中删除
const handleRemove = (todo) => {
const newTodos = todos.filter((t) => t !== todo);
setTodos(newTodos);
}
更新数组
const handleUpdate = (index, todo) => {
const newTodos = [...todos];
newTodos[index] = todo;
setTodos(newTodos);
}
对象
const [todos, setTodos] = useState({});
添加到对象
const handleAdd = (todo) => {
const newTodos = Object.assign({}, todos);
newTodos[todo.id] = todo;
setTodos(newTodos);
}
我们也可以使用扩展运算符来创建浅拷贝。
const handleAdd = (todo) => {
const newTodos = {...todos};
newTodos[todo.id] = todo;
setTodos(newTodos);
}
与数组类似,有一个快捷方式可以在一行中完成此操作:
const handleAdd = (todo) => {
setTodos({...todos, [todo.id]: todo});
}
从对象中移除
const handleRemove = (todo) => {
const newTodos = {...todos}
delete newTodos[todo.id]
setTodos(newTodos);
}
更新对象
与添加相同,如果键已经存在,它将覆盖该值。
const handleUpdate = (todo) => {
setTodos({...todos, [todo.id]: todo});
}