所以我正在尝试从本地存储加载一些数据以用于 Chrome 扩展程序。我需要使用这些数据来设置 useState 钩子的初始值。这是我到目前为止尝试过的:
const Popup = (): ReactElement => {
// load state from local storage
let overviewIsOpenLS;
useLayoutEffect(() => {
chrome.runtime.sendMessage({ getFromLocalStorage: 'overviewIsOpen' }, response => {
overviewIsOpenLS = response;
});
}, []);
console.log(overviewIsOpenLS); // returns undefined
// trying to use the value of overviewIsOpenLS as the initial value of this useState
const [overviewIsOpen, setOverviewIsOpen] = useState<boolean>(overviewIsOpenLS);
return <>...
}
我对本地存储中的值进行了两次/三次检查,它是正确的。但是,顶部的 useEffect 在这一点上不起作用,变量保持未定义。知道如何实现这一目标吗?
答案 0 :(得分:1)
我会在父组件中发出异步请求,然后仅在请求完成后有条件地呈现子组件(Popup
):
// parent component
const [overviewIsOpenLS, setOverviewIsOpenLS] = useState();
useLayoutEffect(() => {
chrome.runtime.sendMessage({ getFromLocalStorage: 'overviewIsOpen' }, setOverviewIsOpenLS);
}, []);
return overviewIsOpenLS === undefined ? null : <Popup overviewIsOpenLS={overviewIsOpenLS} />;
// then in Popup:
const [overviewIsOpen, setOverviewIsOpen] = useState<boolean>(props.overviewIsOpenLS);