SetState的一个对象的数组在React



所以我一直在这个工作了一段时间,我想做的是改变复选框点击的选中值。

我的初始状态是这样的:

const [todoList, setTodoList] = useState({
foundation: {
steps: [
{ key: "1", title: "setup virtual office", isDone: false },
{ key: "2", title: "set mission and vision", isDone: false },
{ key: "3", title: "select business name", isDone: false },
{ key: "4", title: "buy domain", isDone: false },
],
},
discovery: {
steps: [
{ key: "1", title: "create roadmap", isDone: false },
{ key: "2", title: "competitor analysis", isDone: false },
],
}
});

和我的地图和onClick函数(updateCheckFoundation工作时,点击复选框)

{todoList.foundation.steps.map((item) => {
return (
<div>
<input type="checkbox" defaultChecked={item.isDone}
onClick={(event)=> updateCheckFoundation({
isDone:event.target.checked, 
key:item.key
})}/>
<span>{item.title}</span>
</div>
);
})}

如何更新todoList使用setState?

我的代码(updateCheckFoundation func.)是这样的,不工作:(:

const updateCheckFoundation = ({isDone, key}) => {
const updateTodoList = todoList.foundation.steps.map((todo)=> {
if(todo.key === key){
return {
...todo,
isDone
};
}
return todo;
});
setTodoList(updateTodoList);

}

Issue

你的updateCheckFoundation回调并没有保持状态不变,事实上,除了foundation.steps的状态数组外,所有的状态都被删除了。

const updateCheckFoundation = ({isDone, key}) => {
const updateTodoList = todoList.foundation.steps.map((todo)=> {
if(todo.key === key){
return {
...todo,
isDone
};
}
return todo;
});
setTodoList(updateTodoList); // <-- only the state.foundation.steps array!!
}
<标题>

解决方案在函数组件中,当使用useState状态更新器函数时,您需要手动处理合并状态(根状态)和嵌套状态。

const updateCheckFoundation = ({ isDone, key }) => {
setTodoList(state => ({
...state, // <-- shallow copy state object
foundation: {
...state.foundation, // <-- shallow copy
steps: state.foundation.steps.map(todo => todo.key === key
? { ...todo, isDone }
: todo)
},
}));
}