簡體   English   中英

在React掛鈎中將新值推送到嵌套數組

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

我有一個函數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 };
     }));
   };

現在,我想更改功能並可以使用許多標簽。 我應該如何修改函數以將新標簽值推送到新的嵌套標簽:數組。

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

  };

傳播前一個標簽,然后將selectedTag添加到結尾

只是改變這個

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

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

要么

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

您可以使用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