首页 > 解决方案 > 使用 React 状态使用数组更新对象

问题描述

我有一个状态quiz和另一个状态,questionList下面的测验结构是这样的:

const [quiz, setQuiz] = useState({
        title: 'test',
        description: 'test',
        user_id: 'test',
        thumbnail: 'test',
        timer: 'test',
        question: []
    })

不知何故,结构questionList是:

[{
   id: Math.floor(100000 + Math.random() * 900000),
   question: "data",
   answer1: "data",
   answer2: "data",
   answer3: "data",
   answer4: "data"
},
{
   id: Math.floor(100000 + Math.random() * 900000),
   question: "data",
   answer1: "data",
   answer2: "data",
   answer3: "data",
   answer4: "data"
}
]

所以有了一个函数,我正在填充,questionList但我想要做的也是在状态中用新数组更新(或替换question: [])。questionListquiz

这是我在列表中添加问题的方法:

const addQuestion = (question) => {
   setQuestionList([...questionList, question]);   
   // here the logic to update the property question on Quiz state with the new added object into questionList
};

所以当一个问题被添加到列表中时,我想将该列表数组更新为问题:[],作为更新,而不是添加另一个字段。

标签: reactjs

解决方案


您可以使用useEffect带有 questionList 状态的钩子。当 questionList 更新时,这个钩子会触发并更新测验状态。

React.useEffect(()=>{
  setQuiz({...quiz, question: questionList})
}, [questionList]);

推荐阅读