简体   繁体   English

在React挂钩中将新值推送到嵌套数组

[英]Push a new value to nested array in React hooks

I have a function onTagSelected() that updates now a single value for a key inside a object: 我有一个函数onTagSelected(),现在可以更新对象内某个键的单个值:

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']

  };

spread the previous tag and add selectedTag to end 传播前一个标签,然后将selectedTag添加到结尾

just change this 只是改变这个

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

to

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

Or 要么

return { ...x, tag: x.tag.concat(selectedTag) };

You can use es6 destructuring to add new items to an array. 您可以使用es6解构将新项目添加到数组。

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

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

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