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

i can't save items in local storage in 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

您的线路:

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 更改时都设置 LocalStorage,您可以使用 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(这将 运行 一个 side-effect 函数,只要依赖数组中的任何变量发生变化,在本例中为 Todos):

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

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

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

你可以试试:

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