簡體   English   中英

如何在 React state 中動態更新數組中的 Object

[英]How to update Object in Array dynamically in React state

我對 ReactJS 還很陌生,我寫了這個 function 我想用它來更新我的 Z97369E2A5074C17A94F14Z 中的 object。 似乎無法使用“名稱”參數來更新我的 object,我真的不明白為什么。 我也嘗試用模板文字對其進行編碼。

const handleAccountingChange = (newValue, name, id) => {
const newState = selected.map((obj) => {
  if (obj.id === id) {
    return { ...obj, name: newValue };
  }
  return obj;
});
setSelected(newState);

};

我在瀏覽器控制台中沒有收到任何錯誤,但它也沒有更新我的 state。 任何想法都將不勝感激我在谷歌上花了 2 個小時但沒有找到任何東西

當您調用obj.property = 'aaa'時,您將property設置為aaa 您嘗試做的是更新變量name所包含的屬性,您的代碼所做的是更新屬性name

要從變量更新屬性,您需要使用:

const property = 'name'
obj[property] = 'aaa'

相當於:

obj.name == 'aaa'

此代碼解決了您的問題:

 const handleAccountingChange = (newValue, name, id) => { // For the exemple I declare selected here const selected = [ {id: 1, test: 'aaa'}, {id: 2, test: 'bbb'} ]; const newState = selected.map((obj) => { if (obj.id === id) { let myObj = {...obj}; myObj[name] = newValue; return myObj; } return obj; }); return newState; // instead ou can use setSelected(newState) }; console.log(handleAccountingChange('ccc', 'test', 1));

const handleAccountingChange = (newValue, name, id) => {
const newState = selected.map((obj) => {
if (obj.id === id) {
return { obj[name]= newValue};
}
return obj;
});
setSelected({...newState});
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM