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

时间:2019-08-20 10:22:58

标签: javascript reactjs react-hooks

我有一个函数onTagSelected(),它现在可以更新对象内某个键的单个值:

image: java:8

clone:
  depth: full  # SonarCloud scanner needs the full history to assign issues properly

definitions:
  caches:
    sonar: ~/.sonar/cache  # Caching SonarCloud artifacts will speed up your build
  steps:
    - step: &build-test-sonarcloud
        name: Build, test and analyze on SonarCloud
        caches:
          - gradle
          - sonar
        script:
          - ./gradlew clean test
          - ./gradlew jacocoTestReport
          - ./gradlew sonarqube
        artifacts:
          - build/libs/**

pipelines:
  default:
    - step: *build-test-sonarcloud

现在,我想更改功能并可以使用许多标签。我应该如何修改函数以将新标签值推送到新的嵌套标签:数组。

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

2 个答案:

答案 0 :(得分:2)

扩展前一个标签,然后将selectedTag添加到末尾

只需更改此

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

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

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

答案 1 :(得分:1)

您可以使用es6解构将新项目添加到数组中。

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