存储在本地存储中的数据返回未定义,直到在 React 中重新加载页面

问题描述 投票:0回答:1

我正在开发一个应用程序,该应用程序在登录时将角色存储到本地存储。该角色应该将用户重定向到所需的页面。但保存时,它返回为

undefined
。我必须重新加载页面才能检查主要角色
auth.role === 'admin'

有什么方法可以让我在不返回

undefined
路线的情况下完成这项工作吗?

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 },
            }}
          />
        )
      }
    />
  )
}

这是我的

signIn
功能:

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)
  }
reactjs react-redux local-storage lazy-loading react-context
1个回答
-1
投票

如果本地存储的数据发生更改,可以使用带有依赖项的 useEffect hook 来触发 useEffcet 对当前角色的 setRole 更改

```
 useEffect(()=>{
 storageRole=JSON.parse(localStorage.getItem("role"))
  setRole(storageRole) //you can store role of user in state as role and 
  setRole
  },[storageRole])

 ```
© www.soinside.com 2019 - 2024. All rights reserved.