简体   繁体   English

LocalStorage 不持久

[英]LocalStorage does not persist

I have been trying to persist my token in the localStorage but everytime I referesh the page, the value turns to undefined.我一直在尝试将我的令牌保留在 localStorage 中,但每次我引用页面时,该值都会变为未定义。

Here is my code from App.tsx .这是我来自App.tsx的代码。 I am using redux in my project but persisting using redux throws plenty of type errors.我在我的项目中使用 redux,但坚持使用 redux 会引发大量类型错误。 That is why I am going with local storage.这就是为什么我要使用本地存储。

  const [isLoggedIn, setIsLoggedIn] = useState('');
  // @ts-ignore
  const user = useAppSelector(state=>state.user.currentUser.token);
  useEffect(()=>{
    const getToken = localStorage.getItem("token");
    if(getToken){
      setIsLoggedIn(getToken)
    }
  },[])

  useEffect(()=>{
    localStorage.setItem("token", user)
  },[user])

For extra reference, these are my routes作为额外参考,这些是我的路线

        <Route path="/userProfile" element={<UserProfile />} />
        <Route path="/login" element={user ? <Navigate to="/" /> : <Login />} />
        <Route path="/cart" element={<Cart />} />
        <Route path="/" element={<Home />} />
        <Route path="/product/:id" element={<SingleProduct />} />       

So far I have tried all that I know but I am still not able to figure out the root problem.到目前为止,我已经尝试了所有我所知道的,但我仍然无法找出根本问题。

  useEffect(()=>{
    localStorage.setItem("token", user)
  },[user])

Your problem is from the above useEffect .您的问题来自上述useEffect Although it has dependency user (which is listening to user state changes), it's called when you render the component for the first time.虽然它有依赖user (它正在监听user状态更改),但它在您第一次渲染组件时被调用。

I'd propose you should add a condition to that useEffect like below我建议您应该为该useEffect添加一个条件,如下所示

  useEffect(()=>{
    if(user) {
       localStorage.setItem("token", user)
    }
  },[user])

That would help you to prevent calling setItem with an undefined value of user .这将帮助您防止使用未定义的user值调用setItem

检查用户未定义

user && localStorage.setItem("token", user)

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

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