[英]How to make useEffect listening to any change in localStorage?
I am trying to have my React app getting the todos array of objects from the localStorage and give it to setTodos.我正在尝试让我的 React 应用程序从 localStorage 获取 todos 对象数组并将其提供给 setTodos。 To do that I need to have a useEffect that listen to any change that occurs in the local storage so this is what I did:
为此,我需要一个 useEffect 来监听本地存储中发生的任何更改,所以这就是我所做的:
useEffect(() => {
if(localStorage.getItem('todos')) {
const todos = JSON.parse(localStorage.getItem('todos'))
setTodos(todos);
}
}, [ window.addEventListener('storage', () => {})]);
The problem is that useEffect is not triggered each time I add or remove something from the localStorage.问题是每次我在 localStorage 中添加或删除某些内容时都不会触发 useEffect。 Is this the wrong way to have useEffect listening to the localStorage?
这是让 useEffect 监听 localStorage 的错误方式吗?
I tried the solution explained here but it doesn't work for me and I sincerely I do not understand why it should work because the listener is not passed as a second parameter inside the useEffect我尝试了此处解释的解决方案,但它对我不起作用,我真诚地不明白为什么它应该起作用,因为侦听器未作为 useEffect 中的第二个参数传递
You can't re-run the useEffect
callback that way, but you can set up an event handler and have it re-load the todos
, see comments:您不能以这种方式重新运行
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);
};
}, []);
Beware that the storage
event only occurs when the storage is changed by code in a different window to the current one.请注意,仅当存储被不同window 中的代码更改为当前存储时,才会发生
storage
事件。 If you change the todos
in the same window, you have to trigger this manually.如果您更改同一
todos
中的待办事项,则必须手动触发此操作。
const [todos, setTodos] = useState();
useEffect(() => {
setCollapsed(JSON.parse(localStorage.getItem('todos')));
}, [localStorage.getItem('todos')]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.