本地存储中的渲染/更新列表

时间:2020-08-23 23:44:35

标签: reactjs

我正在尝试基于名为todos的对象呈现列表。我希望在用户离开页面后继续保持这种状态。当用户添加待办事项对象时,它将被本地保存并用于使用状态更新待办事项对象。待办事项没有正确显示在列表中,所以我想知道自己在做错什么。

Todos对象:

const [todos, setTodos] = useState([
  {
    text: "Learn about React",
    isCompleted: false,
    id: uuid()
  },
]);

添加功能(在此处更新待办事项,应该重新显示我的列表):

const addTodo = text => {
  setTodos([{text, isCompleted: false, id: uuid()}, ...todos]);   //updates todos object
  localStorage.setItem("currList", JSON.stringify(todos));        //saves new todos object
  storedCurrList = localStorage.getItem("currList");              //retrieves new object
  parsedList = JSON.parse(storedCurrList);                        //parses object
  setTodos(parsedList);                                           //updates based on local save
};                                                                //object so that the update persists

呈现待办事项的组件:

{todos.map((value, index) => {
   return(
     <ListItem key={todos.id}> 
       <ListItemIcon>
         <Checkbox
           edge="start"
           checked={value.isCompleted}
           onChange={() => removeTodo(index)}
           tabIndex={-1}
           disableRipple
          />
       </ListItemIcon>
       <ListItemText disableTypography style={{fontFamily: 'Work Sans', fontSize: 35, color: nightMode.listText}} primary={value.text}/>
     </ListItem>
   );
 })}

1 个答案:

答案 0 :(得分:2)

如果您不想从todos渲染localStorage,则必须先阅读它,然后将其设置为初始todos状态。

const [todos, setTodos] = React.useState([]); // todos are empty by default

React.useEffect(() => {
  // reads the todos saved from localStorage and set that as the new value
  // of our todos state — if currList not found, will fallback to empty list
  const savedTodos = JSON.parse(localStorage.getItem("currList")) || [];
  setTodos(savedTodos);
}, []);

现在,在更新todos上的localStorage时,请将addTodo处理程序更改为

const addTodo = text => {
  // we'll use this to update our `todos` state and `localStorage` 
  const newTodos = [
    { text: input, isCompleted: false, id: uuid() },
    ...todos
  ];

  setTodos(newTodos);
  localStorage.setItem("currList", JSON.stringify(newTodos));
};


在您的addTodo函数上执行此操作(下面的代码)时,即使您调用{{},您设置为todos的{​​{1}}仍是未更新的localStorage 1}}。

todos

我创建了一个代码框供您结帐,希望您能明白。

Edit nice-shirley-mvrnb