繁体   English   中英

坚持 localStorage 与 useContext 不工作

[英]Persist localStorage with useContext not working

刷新嵌套页面时,我一直在努力解决 React Context 值消失的问题。 所以我尝试使用 localsStorage。 为什么它仍然不起作用。 我试图将数据存储在我的应用程序组件中并将其传递给<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 };

我的嵌套页面: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;




看起来在初始渲染期间, info object 具有未定义的值。

这就是为什么在重新加载页面时它没有任何价值。

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

在将其设置为localStorage之前,请检查info值。

暂无
暂无

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

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