【发布时间】:2021-11-30 09:28:10
【问题描述】:
我正在尝试更新存储在我的 useState 挂钩“项目”中的对象。代码块 1 不起作用,但代码块 2 起作用。我唯一做的就是将我的项目放入一个新变量中。有人可以解释为什么代码块 1 不起作用,但代码块 2 起作用。
不工作
const Users = () => {
const [items, setItems] = useState('');
const folder = {
id: itemId,
title: text,
location: itemLocation,
};
// get object index
const objIndex = items.findIndex(obj => obj.location === itemLocation);
// update object
items[objIndex] = folder;
// set state with update
setItems([...items]);
};
以下作品
const Users = () => {
const [items, setItems] = useState('');
const folder = {
id: itemId,
title: text,
location: itemLocation,
};
// put state into variable
const myItems = [...items]
// get object index
const objIndex = items.findIndex(obj => obj.location === itemLocation);
// update object
myItems[objIndex] = folder;
// set state with update
setItems(myItems);
};
【问题讨论】:
标签: javascript reactjs react-native