简体   繁体   English

在 React 中重新加载页面时无法处理复选框的 state

[英]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 保存在本地存储中的待办事项列表数组中,如下所示。

  • todoList is the state that I store each todo. todoList 是我存储每个 todo 的 state。
  • isCompleted also a state with default boolean value of false isCompleted 也是一个 state,默认 boolean 值为 false
 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])
  • This is the checkbox that should change read status.这是应该更改读取状态的复选框。
  <FormControlLabel
       control={
       <Checkbox
       onChange={(e) => changeStatus(e.target.checked,index)}
       color="primary"
        />
       }
  />
  • This is the function supposed to change status.这是 function 应该改变状态。 Click handler works fine, it changes status with each click.单击处理程序工作正常,每次单击都会更改状态。 However, the problem is when I refresh the page, checkbox resets itself to empty state even though status of todo completed in local storage.但是,问题是当我刷新页面时,复选框将自身重置为空 state 即使待办事项的状态在本地存储中完成。
 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));
    }
  • note that I'm mapping itemsToRender array to display todos in the component.请注意,我正在映射 itemsToRender 数组以在组件中显示待办事项。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM