Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当chrome.storage.local中的数据发生更改时,使用effect更新状态_Javascript_Reactjs_Google Chrome Extension_React Hooks_Use Effect - Fatal编程技术网

Javascript 当chrome.storage.local中的数据发生更改时,使用effect更新状态

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) =>

我有这个代码,它工作得非常好,但是当我更新本地存储中的某些内容时,除非我重新加载应用程序,否则我的应用程序不会得到更新。我想做的是,当chrome存储中的数据发生变化时,立即自动更新我应用程序中的数据:

    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')));
});