Push a new value to nested array in React hooks

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-05 08:15:26

问题


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

const NotesContainer = ({

}) => {
  const [notesDummyData, setNotesDummyData] = useState([
    {
      id: '5',
      title: 'Sauna',
      tag: 'relax',
    },
    {
      id: '7',
      title: 'Finland',
      tag: 'nordics'
    },
  ]);

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

Now I would like to change the function and be able to take many tags. How should I go about modify the function to push new tag values to the new nested tag: array.

    const [notesDummyData, setNotesDummyData] = useState([
    {
      id: '5',
      title: 'Sauna',
      tag: ['relax', 'wellness']
    },
    {
      id: '7',
      title: 'Finland',
      tag: ['nordics', 'winter']
    },
  ]);


    const onTagSelected = (selectedTag, itemId) => {

    // Push new tag to nested array for specific item -> tag: ['nordics', 'winter', 'selectedTag']

  };

回答1:


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) };



回答2:


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] };
     }));
  }


来源:https://stackoverflow.com/questions/57571525/push-a-new-value-to-nested-array-in-react-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!