简体   繁体   English

当 chrome.storage.local 中的数据发生变化时,使用 Effect 更新 state

[英]useEffect to to update a state when data in chrome.storage.local changes

i have this code which works perfectly fine, but when i update something in the local storage my app doesnt get updated unless i reload the app.我有这段代码可以正常工作,但是当我更新本地存储中的某些内容时,除非我重新加载应用程序,否则我的应用程序不会更新。 What i want to do is to automatically update the data in my app as soon as the data in chrome storage changes:我想要做的是在 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])

I've put together an example how to use chrome.storage in React app.我已经整理了一个如何在 React 应用程序中使用 chrome.storage 的示例。 There is a listener that listens to changes (which can be triggered with content and/or background script).有一个监听器可以监听变化(可以通过内容和/或后台脚本触发)。 Second listener fetches the current data when component mounts.第二个侦听器在组件挂载时获取当前数据。

import React, { useState } from "react";

const App = () => {
  const [storageData, setStorageData] = useState();

  // Effect 1: Attech/remove storage onChanged listener
  useEffect(() => {
    const listener = () => {
      chrome.storage.sync.get(["storageData"], (result) => {
        setStorageData(result.storageData);
      })
    };
    chrome.storage.onChanged.addListener(listener);
    return () => {
      chrome.storage.onChanged.removeListener(listener);
    };
  }, []);

  // Effect 2: Sync local state with storage data on mount
  useEffect(() => {
    // 'sync' can be 'local', depends on your usecase
    chrome.storage.sync.get(["storageData"], (result) => {
      setStorageData(result.storageData);
    })
  }, []);
  
  // Example event handler to update the storage
  const someEventHandler = (event) => {
    chrome.storage.sync.set({ storagedata: event.target.value}, () => {
      alert("storage updated")
    })
  }

  return (
    <div>
      <pre>{JSON.stringify(storageData, null, 2)}</pre>
      {/* ... */}
    </div>
  );
};

You will need to listen to onstorage event from your window, and apply the logic you need there您需要从 window 监听 onstorage 事件,并在那里应用您需要的逻辑

https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event

window.onstorage = () => {
  // When local storage changes, dump the list to
  // the console.
  console.log(JSON.parse(window.localStorage.getItem('sampleList')));
};

or或者

window.addEventListener('storage', () => {
  // When local storage changes, dump the list to
  // the console.
  console.log(JSON.parse(window.localStorage.getItem('sampleList')));
});

Please refer to this answer too: https://stackoverflow.com/a/56662261/1540560也请参考这个答案: https://stackoverflow.com/a/56662261/1540560

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM