我正在尝试让我的 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 的错误方式吗?
我尝试了解决方案 explained here但它对我不起作用,我真诚地不明白为什么它应该起作用,因为监听器没有作为 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);
};
}, []);
注意 storage
event仅当存储在不同窗口中的代码更改为当前窗口时才会发生。如果您在同一窗口中更改 todos
,则必须手动触发。
关于javascript - 如何让 useEffect 监听 localStorage 的任何变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67683616/