首页 > 解决方案 > 如何实现 localStorage 同步器

问题描述

我想用我的 App.js 实现我的 useLocalStorage 文件,但我无法理解如何做到这一点,因为我还在学习。

使用LocalStorage.js

import { useState, useEffect } from "react";


function useLocalStorage(key, firstValue = null) {
    const initialValue = localStorage.getItem(key) || firstValue;
  
    const [item, setItem] = useState(initialValue);
  
    useEffect(function setKeyInLocalStorage() {
      console.debug("hooks useLocalStorage useEffect", "item=", item);
  
      if (item === null) {
        localStorage.removeItem(key);
      } else {
        localStorage.setItem(key, item);
      }
    }, [key, item]);
  
    return [item, setItem];
  }
  
  export default useLocalStorage;

应用程序.js

import useLocalStorage from "./hooks/useLocalStorage";

const App = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(axios());
  }, []);

  return (
    <BrowserRouter>
      <LastLocationProvider>
        <Navbar />
        <Routes />
        <Footer />
      </LastLocationProvider>
    </BrowserRouter>
  );
};

export default App;

您可以通过的任何提示或知识将不胜感激!

标签: node.jsreactjsredux

解决方案


推荐阅读