[英]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.