如何使用useState将对象添加到位于另一个数组内部的数组中-React Native

时间:2020-02-12 16:58:01

标签: reactjs react-native react-hooks

我想知道如何使用useState将对象推送到位于另一个数组内部的数组。 下面是我的代码:

import React, {useState} from 'react';

const Context = React.createContext();

export const Provider = ({children}) =>{

  const [categories, setCategory] = useState([
    { title: 'Personal' , id: Math.floor(Math.random()* 99999), notes: [
      { noteTitle: 'stam', 
        noteContent: 'stamstamstam',
        id: Math.floor(Math.random()* 99999)
      },
      { noteTitle: 'stam2',
        noteContent: 'stamstamstam232323',
        id: Math.floor(Math.random()* 99999)
      }
    ]},
    { title: 'Work' , id: Math.floor(Math.random()* 99999), notes: []},
    { title: 'Shopping' , id: Math.floor(Math.random()* 99999), notes: []}
  ]);

  const addNoteForCategory = (name, content, categoryId) => {
    const chosenCategory = categories.find((category) => category.id === categoryId)  
    setCategory([...chosenCategory.notes, {
      noteTitle: name, 
      noteContent: content, 
      id: Math.floor(Math.random()* 99999)
    }])
  }

}

2 个答案:

答案 0 :(得分:2)

您可以使用map并更改要更改的项目,然后更新状态。

const updatedCategories = categories.map(category => {
    if (category.id === 123) {
        return {
            ...category,
            notes: [
                ...category.notes,
                { title: 'Note 2' }
            ]
        }
    }

    return category;
});

setCategory(updatedCategories);

您需要用您的特定数据替换我使用的虚拟ID和数据。

答案 1 :(得分:0)

const addNoteForCategory = (name, content, categoryId) => {
      setCategory( prevState => {
        const chosenCategory = prevState.find((category) => category.id === categoryId);
        chosenCategory.notes.push({
          noteTitle: name, 
          noteContent: content, 
          id: Math.floor(Math.random()* 99999)
        });
        return prevState
    });

  }