[英]How to update an object and set the state with new object values using React or React Native
我正在嘗試更新存儲在我的 useState 掛鈎“項目”中的 object。 代碼塊 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);
};
items[objIndex] = folder;
你永遠不應該像這樣直接更新 state。 React 假設你總是使用“set”函數來更新你的 state,並且如果你直接修改 state 將不知道何時重新渲染你的組件。
https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly
// update object
items[objIndex] = folder;
我相信這是問題所在。 實際上,我從未嘗試更改 state 本身(我一直認為它是只讀的)。
稍后我將對此進行進一步測試以確定。 但通常您不會直接編輯 state(state 表示items
變量)。 要么您 1) 創建一個items1
,例如items1 = {...items }
然后setItems(items1[objIndex] = folder)
要么按照您在第二個代碼片段中的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.