Push a new value to nested array in React hooks

前端 未结 2 1753
我寻月下人不归
我寻月下人不归 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] };
         }));
      }
    
    0 讨论(0)
  • 2021-01-27 03:50

    spread the previous tag and add selectedTag to end

    just change this

    return { ...x, tag: selectedTag };
    

    to

    return { ...x, tag: [...x.tag, selectedTag] };
    

    Or

    return { ...x, tag: x.tag.concat(selectedTag) };
    
    0 讨论(0)
提交回复
热议问题