我正在react.js 中做一个简单的Todolist。到目前为止我能够保存我的对象 到 LocalStorage,但是当我刷新页面时,Todo 元素消失了。
import React, { useState,useEffect } from 'react'
import TodoList from './TodoList.jsx'
const AddTodo = () => {
const [newTodo, setNewTodo] = useState('')
const [list, setList] = useState([])
const handleSubmit = () => {
const todoItem = {
id:Math.floor(Math.random() * 10000),
value:newTodo
}
if(todoItem){
setList([...list,todoItem])
setNewTodo('')
}
/*gets the oldlist and whats inside of it and adds the new item */
console.log(list)
}
useEffect(() => {
localStorage.setItem("list", JSON.stringify(list));
}, [list])
useEffect(() => {
const data = JSON.parse(localStorage.getItem('list'));
if(data){
setList(data)
}
}, [])
return (
<div className="input_container">
<form onSubmit={(e) => e.preventDefault()}>
<input type="text"
onChange={e => setNewTodo(e.target.value)}
className="todo-input"
placeholder="Write Todo.."
value={newTodo}
name="text"/>
<button onClick={() => handleSubmit()} className="add-todo-button">
Add Todo
</button>
</form>
<TodoList list={list} newTodo={newTodo}/>
</div>
)
}
export default AddTodo
最佳答案
创建状态时,您必须从所在状态的本地存储中获取待办事项列表。每次页面刷新时,都会从本地存储获取初始状态。如果它有其他内容,它会将其设置为 []
像这样。
const [newTodo, setNewTodo] = useState('')
const [list, setList] = useState(JSON.parse(localStorage.getItem("list")) || [])
这是一种更好的方法。
关于javascript - React.js : Save items after refreshing page,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72638064/