Push a new value to nested array in React hooks

前端 未结 2 1757
我寻月下人不归
我寻月下人不归 2021-01-27 03:16

I have a function onTagSelected() that updates now a single value for a key inside a object:

const NotesContainer = ({

}) => {
  const [notesDummyData, setNo         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-27 03:46

    You can use es6 destructuring to add new items to an array.

      const onTagSelected = (selectedTag, itemId) => {
         setNotesDummyData(notesDummyData.map((x) => {
           if (x.id !== itemId) return x;
           return { ...x, tag: [...x.tag, selectedTag] };
         }));
      }
    

提交回复
热议问题