正如标题所说,我设置的 localStorage 注册了对todoList数组所做的更改并JSON.stringify保存它;但是,每当我刷新页面时,数组都会返回默认[]状态。
const LOCAL_STORAGE_KEY = "task-list"
function TodoList() {
const [todoList, setTodoList] = useState([]);
useEffect(() => {
const storedList = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
if (storedList) {
setTodoList(storedList);
}
}, []);
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todoList));
}, [todoList]);
Run Code Online (Sandbox Code Playgroud)