Javascript 使用React、React钩子的私有路由

Javascript 使用React、React钩子的私有路由,javascript,reactjs,Javascript,Reactjs,尝试使用react钩子创建经过身份验证的路由,使用下面的代码段,当我刷新页面时,当令牌可用时,它会出现。在第一次呈现时,它不会在useEffect中被拾取。我做错了什么 constauthroute=({component:component,…rest})=>{ const context=useContext(AuthStateContext) const token=window.localStorage.getItem('token') useffect(()=>{ 如果(令牌){ c

尝试使用react钩子创建经过身份验证的路由,使用下面的代码段,当我刷新页面时,当令牌可用时,它会出现。在第一次呈现时,它不会在useEffect中被拾取。我做错了什么

constauthroute=({component:component,…rest})=>{
const context=useContext(AuthStateContext)
const token=window.localStorage.getItem('token')
useffect(()=>{
如果(令牌){
context.setLogin()
}
日志(“令牌->”,令牌)
}, [])
返回(
(
context.isAuthenticated?
: 
)}
/>
)

}
我假设
context.setLogin()
context.isAuthenticated
设置为
true
。如果是这样的话,那么它就解释了

每次渲染后,
useffect(Callback)
的回调函数总是异步调用。从第一次渲染开始,
setLogin()
仅在读取
isAuthenticated
的值后调用,在访问时该值应为
false

所以渲染逻辑转到第二个分支
,它会立即将用户带到其他地方

要实现这一点,您可以推迟决定
isAuthenticated
的呈现util状态

(这里,我假设您希望在渲染树的早期检查并设置一次
isAuthenticated
,然后通过
AuthStateContext
广播
isAuthenticated
对象,让应用程序的其他部分注意。)

我建议采用这种模式:

const AuthRoute = ({ component: Component, ...rest }) => {
  const context = useContext(AuthStateContext)
  const [authChecked, setAuthChecked] = useState(false)

  useEffect(() => {
    const token = window.localStorage.getItem('token')
    if (token) context.setLogin()
    setAuthChecked(true)
    console.log("TOKEN ->", token)
  }, [])

  if (!authChecked) return null  // <-- the trick! 

  return (
    <Route
      {...rest}
      render={props => (
        context.isAuthenticated ?
          <Component {...props} />
          : <Redirect to={{
            pathname: "/",
            state: { from: props.location }
          }} />
      )}
    />
  )
}

我假设
context.setLogin()
context.isAuthenticated
设置为
true
。如果是这样的话,那么它就解释了

每次渲染后,
useffect(Callback)
的回调函数总是异步调用。从第一次渲染开始,
setLogin()
仅在读取
isAuthenticated
的值后调用,在访问时该值应为
false

所以渲染逻辑转到第二个分支
,它会立即将用户带到其他地方

要实现这一点,您可以推迟决定
isAuthenticated
的呈现util状态

(这里,我假设您希望在渲染树的早期检查并设置一次
isAuthenticated
,然后通过
AuthStateContext
广播
isAuthenticated
对象,让应用程序的其他部分注意。)

我建议采用这种模式:

const AuthRoute = ({ component: Component, ...rest }) => {
  const context = useContext(AuthStateContext)
  const [authChecked, setAuthChecked] = useState(false)

  useEffect(() => {
    const token = window.localStorage.getItem('token')
    if (token) context.setLogin()
    setAuthChecked(true)
    console.log("TOKEN ->", token)
  }, [])

  if (!authChecked) return null  // <-- the trick! 

  return (
    <Route
      {...rest}
      render={props => (
        context.isAuthenticated ?
          <Component {...props} />
          : <Redirect to={{
            pathname: "/",
            state: { from: props.location }
          }} />
      )}
    />
  )
}

是的isAuthenticated是布尔值,谢谢你的帮助。是的isAuthenticated是布尔值,谢谢你的帮助。谢谢你的帮助。