改变反应状态以不变的方式
我有一个状态,该状态由 exam 对象的数组组成,它的参数之一( tasks )也是对象的数组。我需要以不可变的方式更改一个对象( essivs )中一个参数数组( tasks )的一项( tasks )的参数。感谢您的帮助。
const changeTaskStatus = useCallback((id) =>{
setExams(prev => prev.map((exam) =>{
if (exam.tasks.find(task => task.id === id)) {
const examCopy = {...exam};
examCopy.tasks.map(task => {
if (task.id === id) {
const taskCopy = {...task};
task.status = true;
return taskCopy
} else {
return task
}
})
return examCopy;
} else {
return exam
}
}))
}, [setExams])
I have a state which consists of array of Exam objects one of parameters of it (tasks) is array of objects too. I need to change parameter (status) of one item of parameter array (tasks) in one object (exam) in immutable way. Would appreciate you help.
const changeTaskStatus = useCallback((id) =>{
setExams(prev => prev.map((exam) =>{
if (exam.tasks.find(task => task.id === id)) {
const examCopy = {...exam};
examCopy.tasks.map(task => {
if (task.id === id) {
const taskCopy = {...task};
task.status = true;
return taskCopy
} else {
return task
}
})
return examCopy;
} else {
return exam
}
}))
}, [setExams])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想更新与ID匹配的所有任务的状态,则这里有一个解决方案:
完整的沙箱-e href =“ https://codesandbox.io/s/cranky-water-0qhzh0?file=/src /app.js:432-742“ rel =“ nofollow noreferrer”> https://codesandbox.io/s/cranky-water-0qhzh0?file=/src/src/app.js:432-742
If you are looking to update status of all the tasks which matches an id, then here is a solution:
Full sandbox - https://codesandbox.io/s/cranky-water-0qhzh0?file=/src/App.js:432-742