简体   繁体   English

坚持 localStorage 与 useContext 不工作

[英]Persist localStorage with useContext not working

I've been struggling with React Context value disappears when refresh my nested page.刷新嵌套页面时,我一直在努力解决 React Context 值消失的问题。 So i tried to use localsStorage.所以我尝试使用 localsStorage。 Why is it still not working tho.为什么它仍然不起作用。 I have tried to store data in my app component and pass it to <InfoDetails> , it works perfectly fine, but when i refresh the page, the data is gone.我试图将数据存储在我的应用程序组件中并将其传递给<InfoDetails> ,它工作得很好,但是当我刷新页面时,数据就消失了。

function InfoContextProvider(props) {
  const { food } = useHttp("food");
  const { location } = useHttp("location");

  const info = {
    Food: food,
    Location: location,
  };

  useEffect(() => {
    localStorage.setItem("info", JSON.stringify(info));
  }, [info]);

  return (
    <InfoContext.Provider value={{ info }}>
      {props.children}
    </InfoContext.Provider>
  );
}

export { InfoContextProvider, InfoContext };

my nested page:id/:productname/我的嵌套页面:id/:productname/



const InfoDetails = (props) => {
  const { id, productname } = useParams();
  const { info } = useContext(InfoContext);

  const item = JSON.parse(localStorage.getItem("info"));


  const data = item[id].find((name) => name.name === productname);



  return (
    <>
      <div className={classes.container}>
          <img src={data.image} alt="" />
     </div>
    </>
  );
};

export default InfoDetails;




Looks like during initial render, the info object has undefined value.看起来在初始渲染期间, info object 具有未定义的值。

That's why it has no value when reloading the page.这就是为什么在重新加载页面时它没有任何价值。

function InfoContextProvider(props) {
  const { food } = useHttp("food");
  const { location } = useHttp("location");

  const info = {
    Food: food,
    Location: location,
  };

  useEffect(() => {
     if(info.Food && info.Location) {
       localStorage.setItem("info", JSON.stringify(info));
     }
  }, [info]);

  return (
    <InfoContext.Provider value={{ info }}>
      {props.children}
    </InfoContext.Provider>
  );
}

export { InfoContextProvider, InfoContext };

Do check the info value before setting it into the localStorage .在将其设置为localStorage之前,请检查info值。

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

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