簡體   English   中英

React - 在數組中更新 object 中的 object

[英]React - update object within object within array

在更新一個字段時遇到問題,該字段的值如果在數組中的 object 中的 object 中:

      [
        { animals: { an1: 'lynx', an2: 'tiger' }, location: 'asia' },
        { animals: { an1: 'pigeon', an2: 'eagle' }, location: 'europe' },
      ];
const handleChange = (e, input) => {
    let updatedList = data.map((item, i) => {
        if (i === index) {
          const allAnimals = { ...item.animals };
          allAnimals[input] = e.target.value;

          return { ...item, animals: allAnimals }; 
        }
        return item;
      });
    
    setData(updatedList);

  }

我將如何更新animals an2中的an1或 an2?

如果您只是想替換所有索引,則以下應該有效:

 const data = [ { animals: { an1: 'lynx', an2: 'tiger' }, location: 'asia' }, { animals: { an1: 'pigeon', an2: 'eagle' }, location: 'europe' }, ]; const handleChange = (e, input) => data.map(it => ({...it, animals: {...it.animals, [input]: e.target.value, } })) console.log(handleChange({ target: { value: 'test', }}, 'an2' ))

請注意,這會將新值替換/添加到每個數組。

暫無
暫無

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

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