我无法在 React js 中将项目保存在本地存储中

我在 Reactjs 中创建了一个待办事项应用程序,并将包含数据的对象保存在本地存储中,但问题是在重新加载页面后,包含本地存储中项目的数组被重置并再次变为空

家庭组件:

import React, { Component } from 'react';
import Form from "./Form"
import TodoList from "./TodoList"
import { useState } from 'react';

function Home() {
const [inputText,setInputText] = useState("")
const [Todos,setTodos] = useState([])
localStorage.setItem('Todos', JSON.stringify(Todos));
const localStorageData = JSON.parse(localStorage.getItem("Todos"))

const Tasks = localStorageData.map(function(i){
 return <TodoList value={i.text}/>
})
return(
<div>
<Form inputText={inputText} setInputText={setInputText} Todos={Todos} setTodos={setTodos}/>
{Tasks}
</div>
)

}

export default Home
stack overflow i can't save items in local storage in react js
原文答案
author avatar

接受的答案

你可以试试:

import React, { Component, useEffect } from 'react';
import Form from "./Form"
import TodoList from "./TodoList"
import { useState } from 'react';

function Home() {
const [inputText,setInputText] = useState("")
const [Todos,setTodos] = useState([])
//useEffect(function (){}, []) this hook takes function as its first argument and an array/dependency as 
//which if the [] arrray is empty it runs once, meaning on initial render
useEffect(() => {
  const previousData = JSON.parse(localStorage.getItem("Todos"));
  setTodos(previousData);
},[])
//and if something changes in the dependency's value in this case inputText the function that is passed as the first argument runs each time
useEffect(() => {
 localStorage.setItem('Todos', JSON.stringify(Todos));
}, [inputText])

const Tasks = localStorageData.map(function(i){
 return <TodoList value={i.text}/>
})
return(
<div>
<Form inputText={inputText} setInputText={setInputText} Todos={Todos} setTodos={setTodos}/>
{Tasks}
</div>
)

}

export default Home

答案:

作者头像

您的线路:

localStorage.setItem('Todos', JSON.stringify(Todos));

正在重置本地存储并在刷新时再次设置项目。您可以使用简单的 IF 语句来检查 localStorage 是否为空,然后分配项目来避免这种情况:

if(!localStorage.getItem("Todos") || JSON.parse(localStorage.getItem("Todos")).length === 0){
 localStorage.setItem('Todos', JSON.stringify(Todos));

}
作者头像

这种行为正在发生,因为您试图在组件的根目录中设置本地存储值。如果您想要在每次 Todos 更改时设置本地存储,您可以使用 useEffect 钩子或 set 函数的包装器。

此外,您需要使用 localStorage 值初始化 Todos 状态,以便在重新加载页面时不会将其设置为空数组,如下所示:

const [Todos, setTodos] = useState(
    // if the value returned by JSON.parse is nullish, intialize as an empty array
    JSON.parse(localStorage.getItem('Todos')) ?? [],
);

使用 useEffect(只要依赖数组中的任何变量发生变化,这将运行一个副作用函数,在本例中为 Todos):

useEffect(() => {
    localStorage.setItem('Todos', JSON.stringify(Todos));
}, [Todos]);

使用 wrapper 函数(而不是使用内置的 setTodos 函数,您调用一个设置 Todos 和本地存储值的包装器):

const setTodosWithLocalStorage = useCallback(newTodos => {
    localStorage.setItem('Todos', JSON.stringify(newTodos));
    setTodos(newTodos);
}, []);
作者头像

在本地存储中添加查看或删除数据

  • const textForStorage = "Hello World.";
  • localStorage.setItem("我的文本", textForStorage);
  • const textFormStorage = localStorage.getItem("my-key");
  • localStorage.removeItem("我的文本");
  • const person = { firstName: "john", lasName: "alex" };
  • localStorage.setItem("用户", JSON.stringify(person));
  • localStorage.clear();