【发布时间】:2022-01-31 03:23:12
【问题描述】:
我正在开发一个在登录时将角色存储到本地存储的应用程序。该角色应该将用户重定向到所需的页面。但是在保存时,它返回为未定义。我必须重新加载页面才能检查主要角色auth.role === 'admin。有什么办法可以使这项工作?不返回未定义的路线?
const AdminRoute = ({ children, ...rest }) => {
const auth = useContext(AuthContext)
return (
<Route
{...rest}
render={({ location }) =>
auth.token && auth.role === 'admin' ? (
children
) : (
<Redirect
to={{
pathname: '/',
state: { from: location },
}}
/>
)
}
/>
)
}
这是我的登录功能
const signIn = async (email, password, callback) => {
setLoading(true)
const { data } = await signInApi(email, password)
console.log(data)
if (data && data.token) {
localStorage.setItem('token', data.token)
localStorage.setItem('user', JSON.stringify(data.user))
localStorage.setItem('role', data.user.role)
setToken(data.token)
setUser(data.user)
setUser(data.user.role)
callback()
}
setLoading(false)
}
【问题讨论】:
-
setLoading(false) 不应该在 if(data && data.token) 的刹车之间吗?你几乎在做: setLoading(true) setLoading(false)
-
我不明白。你能帮我修改代码吗?
标签: reactjs react-redux local-storage lazy-loading react-context