[英]Cannot handle state of checkbox upon page reload in React
I'm trying to make a todo list app by using React and Material UI.我正在尝试使用 React 和 Material UI 制作一个待办事项列表应用程序。 Everything works fine except checkbox state.
除了复选框 state 外,一切正常。 I'm saving each todo as object in todo list array in local storage as below.
我将每个待办事项作为 object 保存在本地存储中的待办事项列表数组中,如下所示。
let arr = todoList;
const newTodo = new TodoItem({
id: randomID,
text: text,
date: date,
status: isCompleted
});
setTodoList([newTodo, ...arr]);
localStorage.setItem('todos', JSON.stringify(todoList));
In another component I get saved items from local storage by useEffect and render them as todo list.在另一个组件中,我通过 useEffect 从本地存储中获取保存的项目并将它们呈现为待办事项列表。 I'm trying to get stored items every time isCompleted changes.
每次isCompleted更改时,我都会尝试获取存储的项目。
useEffect(() => {
let savedItem = JSON.parse(localStorage.getItem('todos'))
if (savedItem !== null) {
setTodoList(savedItem);
}
}, [isCompleted])
<FormControlLabel
control={
<Checkbox
onChange={(e) => changeStatus(e.target.checked,index)}
color="primary"
/>
}
/>
const changeStatus = (val,num) => {
let item = todoList[num];
if(val === false){
setIsCompleted(true);
item.status = isCompleted;
}else if(val === true){
setIsCompleted(false);
item.status = isCompleted;
}
let storedItems = [...todoList];
itemsToRender = storedItems;
storedItems = storedItems.map(todo => todo.id === item.id ? todo = item : todo)
console.log('STORED',storedItems);
localStorage.setItem('todos', JSON.stringify(storedItems));
}
How can I prevent checkbox to reset itself(unchecked), I need checkbox to stay checked after reloading the page.如何防止复选框自行重置(未选中),我需要复选框在重新加载页面后保持选中状态。
To me, I'm doing something wrong with useEffect or MUI checkbox component.对我来说,我在 useEffect 或 MUI 复选框组件上做错了。
Thanks in advance for any help or advice.提前感谢您的任何帮助或建议。
You need to make the checkbox a controlled input by specifying the value attribute on it.您需要通过在复选框上指定 value 属性来使复选框成为受控输入。 And set the value attribute equal to the
todo.status
并将 value 属性设置为等于
todo.status
todoList.map(todo =>
(<FormControlLabel
control={
<Checkbox
onChange={(e) => changeStatus(e.target.checked,index)}
color="primary"
value={todo.status}
/>
}
/>)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.