[我在下面编写了一个自定义上下文提供程序,该应用程序将应用程序设置保存为Context
并将其保存在localStorage
中(感谢Alex Krush的post。]
我添加了initialized
标志,以避免在组件安装后立即保存从localStorage
获取的值(useEffect
将在componentDidMount
的时间运行,并尝试将获取的值写入存储器)。
import React, { useCallback, useEffect, useReducer, useRef } from 'react';
const storageKey = 'name';
const defaultValue = 'John Doe';
const initializer = (initialValue) => localStorage.getItem(storageKey) || initialValue;
const reducer = (value, newValue) => newValue;
const CachedContext = React.createContext();
const CachedContextProvider = (props) => {
const [value, setValue] = useReducer(reducer, defaultValue, initializer);
const initialized = useRef(false);
// save the updated value as a side-effect
useEffect(() => {
if (initialized.current) {
localStorage.setItem(storageKey, value);
} else {
initialized.current = true; // skip saving for the first time
}
}, [value]);
return (
<CachedContext.Provider value={[value, setValue]}>
{props.children}
</CachedContext.Provider>
);
};
用法:
const App = (props) => {
return <CachedContextProvider><Name name='Jane Doe' /></CachedContextProvider>;
}
const Name = (props) => {
const [name, setName] = useContext(CachedContext);
useEffect(() => {
setName(props.name);
}, [props.name]);
}
然后,我想让我的自定义上下文检测到另一个窗口对目标存储所做的更改。我将handleStorageEvent
添加到CachedContextProvider
以监听存储事件:
// re-initialize when the storage has been modified by another window
const handleStorageEvent = useCallback((e) => {
if (e.key === storageKey) {
initialized.current = false; // <-- is it safe???
setValue(initializer(defaultValue));
}
}, []);
useEffect(() => {
if (typeof window !== 'undefined') {
window.addEventListener('storage', handleStorageEvent);
return () => {
window.removeEventListener('storage', handleStorageEvent);
};
}
}, []);
我担心的是是否可以安全地将initialized
重置为false
,以避免写回获取的值。我担心多进程设置中的以下情况:
setValue('Harry Potter')
setValue('Harry Potter')
localStorage.setItem
以响应对value
的更新initialized
和value
重新初始化为false
和'Harry Potter'
localStorage.setItem
,但是它没有任何作用,因为Window 2已经将value
设置为'Harry Potter'
,并且React可能会判断没有更改。结果,initialized
将保持为false
setValue('Ron Weasley')
。它更新value
,但initialized === false
。有机会丢失应用程序设置的值useEffect
和DOM事件处理程序之间的执行顺序有关。有人知道该怎么做吗?但是,这是我的理论:在第5步中,窗口1将不会尝试运行localStorage.setItem(如您所说),因为初始化设置只是设置为false。相反,它将设置为true。因此,第6步应该可以按预期工作,这应该不是问题。