javascript - 如何在 React 中的多维数组中添加更多项目
问题描述
大家好,在为时已晚之前,我不能工作。
我需要更新每个复选框,当这是对或错时(任务数组是前端的复选框)
Data seeds
const datas = [
{
id: 10,
name: job01,
tasks: [
{ name: "morning", value: false },
{ name: "afternoon", value: true },
{ name: "sunset", value: false },
{ name: "night", value: true },
],
completed: false
}];
按下一个复选框时,下一个更新数据的代码是:
const [todos, setTodos] = useState(datas)
const toggleTask = taskId => {
const updateTodos = todos.forEach(to => {
to.tasks.forEach(task => {
if (taskId === to.name)
console.log('update datas: ', { ...task, value: !task.value})
}
})
})console.log('Result: ', updateTodos ) };//only show undefined
感谢自述文件。
解决方案
forEach
不返回任何内容,您可能需要先映射数组,然后过滤元素:
// get a list of the tasks that you need to update
const needUpdateTodos = todos.flatMap(
to => to.tasks.filter(task => taskId === to.name)
);
// for each task that you need to update, change the value to the opposite
const updatedTodos = needUpdateTodos.map(el => {
task.value = !task.value;
console.log('update datas: ', task)
return task
})
// show resulting tasks updated
console.log('Result: ', updatedTodos )
推荐阅读
- c# - 从套接字将文本作为二进制数据发送
- oop - 结构在数组中时组件的行为
- email - 下载电子邮件活动的审核日志
- android - Imageview 动态添加到 relativelayout
- azure - AZure AD 连接和 Azure AD 防火墙
- sas - Sas如何处理名称由两部分组成的列,第一部分相同,第二部分不同
- node.js - Meteor 客户端使用 LDAP 和 JWT 登录
- caffe - 如何检查 Caffe 是否正在使用我的 GPU?
- perl - 没有在我的 Mojolicious 应用程序中创建和写入日志文件
- sql-server - 将 ISNULL 包裹在 NULLIF 周围