localstorage不持续
我一直在努力将我的令牌持续到localstorage中,但是每当我引用页面时,该值都会变成未定义的。
这是我的代码来自app.tsx
。我在项目中使用Redux,但使用Redux持续存在很多类型错误。这就是为什么我要去本地存储。
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])
对于额外的参考,到目前为止,我已经尝试了我所知道的所有路线
<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 />} />
,但我仍然无法弄清楚根问题。
I have been trying to persist my token in the localStorage but everytime I referesh the page, the value turns to undefined.
Here is my code from App.tsx
. I am using redux in my project but persisting using redux throws plenty of type errors. 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查用户到未定义
Check user to undefined
您的问题是从上面的
使用效果
。尽管它具有依赖关系用户
(正在收听用户
状态更改),但是当您首次渲染组件时,它是调用的。我建议您在下面的
useffect
上添加条件,这将有助于您防止
setItem
user
。Your problem is from the above
useEffect
. Although it has dependencyuser
(which is listening touser
state changes), it's called when you render the component for the first time.I'd propose you should add a condition to that
useEffect
like belowThat would help you to prevent calling
setItem
with an undefined value ofuser
.