And*_* D_ 4 javascript reactjs
我试图让我的 React 应用程序从 localStorage 获取 todos 对象数组并将其交给 setTodos。为此,我需要有一个 useEffect 来监听本地存储中发生的任何更改,所以这就是我所做的:
useEffect(() => {
if(localStorage.getItem('todos')) {
const todos = JSON.parse(localStorage.getItem('todos'))
setTodos(todos);
}
}, [ window.addEventListener('storage', () => {})]);
Run Code Online (Sandbox Code Playgroud)
问题是每次我从 localStorage 添加或删除某些内容时都不会触发 useEffect 。这是让 useEffect 监听 localStorage 的错误方法吗?
我尝试了此处解释的解决方案,但它对我不起作用,我真诚地不明白为什么它应该起作用,因为监听器没有作为 useEffect 中的第二个参数传递
T.J*_*der 12
您无法以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);
};
}, []);
Run Code Online (Sandbox Code Playgroud)
请注意,仅当存储在与当前窗口不同的窗口中的代码更改时,才会发生该storage事件。如果您在同一窗口中更改,则必须手动触发。todos
| 归档时间: |
|
| 查看次数: |
11977 次 |
| 最近记录: |