Javascript 当chrome.storage.local中的数据发生更改时,使用effect更新状态
我有这个代码,它工作得非常好,但是当我更新本地存储中的某些内容时,除非我重新加载应用程序,否则我的应用程序不会得到更新。我想做的是,当chrome存储中的数据发生变化时,立即自动更新我应用程序中的数据:Javascript 当chrome.storage.local中的数据发生更改时,使用effect更新状态,javascript,reactjs,google-chrome-extension,react-hooks,use-effect,Javascript,Reactjs,Google Chrome Extension,React Hooks,Use Effect,我有这个代码,它工作得非常好,但是当我更新本地存储中的某些内容时,除非我重新加载应用程序,否则我的应用程序不会得到更新。我想做的是,当chrome存储中的数据发生变化时,立即自动更新我应用程序中的数据: const [profiles, setProfiles] = useState([]); useEffect(()=>{ chrome.storage.local.get(["profiles"], (result) =>
const [profiles, setProfiles] = useState([]);
useEffect(()=>{
chrome.storage.local.get(["profiles"], (result) => {
if (result.profiles) {
console.log(result.profiles);
setProfiles( result["profiles"]);
console.log(profiles);
}
});
},[])
//run every time when the data changes
useEffect(()=>{
chrome.storage.local.set({ "profiles": profiles });
console.log("running");
},[profiles])
您需要从窗口侦听onstorage事件,并在其中应用所需的逻辑 或
也请参考此答案:localStorage与OP使用的chrome.storage.local无关。参见
chrome.storage.onChanged
事件示例。
window.onstorage = () => {
// When local storage changes, dump the list to
// the console.
console.log(JSON.parse(window.localStorage.getItem('sampleList')));
};
window.addEventListener('storage', () => {
// When local storage changes, dump the list to
// the console.
console.log(JSON.parse(window.localStorage.getItem('sampleList')));
});