简体   繁体   English

反应:附加到状态数组对象的数组

[英]React: append to a state array object's array

My state looks something like this:我的状态看起来像这样:

const [state, setState] = useState([
 { id: uuidv4(), myList: ["listItem1", "listItem2"] }
 { id: uuidv4(), myList: ["listItem1"] }
])

How can I add a value to myList to the specific object that I want it added?如何将myList的值添加到我想要添加的特定对象?

First, as you need do compute uuid to generate the ids, I would use a function to initialize the state :首先,由于您需要计算 uuid 以生成 id,我将使用一个函数来初始化状态:

const [state, setState] = useState(() => [
 { id: uuidv4(), myList: ["listItem1", "listItem2"] }
 { id: uuidv4(), myList: ["listItem1"] }
])

Then, to add an item to the myList array, I suggest you to add a function like below :然后,要将项目添加到myList数组,我建议您添加如下函数:

function addItem(id, item) {
  const newState = state.map(el => 
      el.id === id ? {...el, myList: [...el.myList, item]} : el
  );
  setState(newState);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM