首页 > 解决方案 > 如何在 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

感谢自述文件。

标签: javascriptarraysreactjsreact-hooks

解决方案


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 )

推荐阅读