[英]How to make useEffect listening to any change in localStorage?
我正在尝试让我的 React 应用程序从 localStorage 获取 todos 对象数组并将其提供给 setTodos。 为此,我需要一个 useEffect 来监听本地存储中发生的任何更改,所以这就是我所做的:
useEffect(() => {
if(localStorage.getItem('todos')) {
const todos = JSON.parse(localStorage.getItem('todos'))
setTodos(todos);
}
}, [ window.addEventListener('storage', () => {})]);
问题是每次我在 localStorage 中添加或删除某些内容时都不会触发 useEffect。 这是让 useEffect 监听 localStorage 的错误方式吗?
我尝试了此处解释的解决方案,但它对我不起作用,我真诚地不明白为什么它应该起作用,因为侦听器未作为 useEffect 中的第二个参数传递
您不能以这种方式重新运行useEffect
回调,但您可以设置一个事件处理程序并让它重新加载todos
,请参阅注释:
useEffect(() => {
// Load the todos on mount
const todosString = localStorage.getItem("todos");
if (todosString) {
const todos = JSON.parse(todosString);
setTodos(todos);
}
// Respond to the `storage` event
function storageEventHandler(event) {
if (event.key === "todos") {
const todos = JSON.parse(event.newValue);
setTodos(todos);
}
}
// Hook up the event handler
window.addEventListener("storage", storageEventHandler);
return () => {
// Remove the handler when the component unmounts
window.removeEventListener("storage", storageEventHandler);
};
}, []);
请注意,仅当存储被不同window 中的代码更改为当前存储时,才会发生storage
事件。 如果您更改同一todos
中的待办事项,则必须手动触发此操作。
const [todos, setTodos] = useState();
useEffect(() => {
setCollapsed(JSON.parse(localStorage.getItem('todos')));
}, [localStorage.getItem('todos')]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.