reactjs - 使用 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: []
)。questionList
quiz
这是我在列表中添加问题的方法:
const addQuestion = (question) => {
setQuestionList([...questionList, question]);
// here the logic to update the property question on Quiz state with the new added object into questionList
};
所以当一个问题被添加到列表中时,我想将该列表数组更新为问题:[],作为更新,而不是添加另一个字段。
解决方案
您可以使用useEffect
带有 questionList 状态的钩子。当 questionList 更新时,这个钩子会触发并更新测验状态。
React.useEffect(()=>{
setQuiz({...quiz, question: questionList})
}, [questionList]);
推荐阅读
- python - 部分 HTML 对 Scrapy 不可见
- entity-framework - EF Core 一对多无限包括
- mysql - 在创建插入之前导入大量数据
- python - 运行python脚本后excel恢复错误
- git - GIT:远程:致命:内存不足,malloc 失败(试图分配 190135255 字节)
- visual-studio - VS UnitTesting a FileContentResult - 我可以在测试时生成文件吗
- android - 如何检查设备是否具有指纹功能,然后在 Android 中使用
- c++ - CMake 找不到库
- elasticsearch - 如何在 filebeat.yml 输入路径中指定 windows 临时文件夹 (%temp%)
- python-3.x - 如何通过从最小二乘线性拟合中提取系数来将多个光谱拟合到光谱中?