簡體   English   中英

如果用戶已登錄 React 和 Typescript,則在刷新時重定向到儀表板

[英]Redirect to dashboard on refresh if user is logged in React and Typescript

我在一個用戶登錄並且令牌存儲在本地存儲中的應用程序上工作。 如果令牌不在本地存儲中,或者如果它是並且它是受保護的路由“/dashboard”是有效的,我希望主頁成為登錄頁面。 我的代碼是:

const App = () => {

  const [authenticated, setAuthenticated] = useState<IState["authenticated"]>(false)   

  useEffect ( () => {
    const token: string | null  = localStorage.getItem('token')   
    if (token)
    {
      setAuthenticated(true)
      window.location.assign("/dashboard")
    }
  }, [authenticated])

  return (
    <div className="App">
      <Router>
        <Routes>
        <Route  path="/" element = {<LogIn setAuthenticated={setAuthenticated}/>} />
        <Route path="/signup" element = {<CreateUser />} />
        <Route path="/forgot_password" element ={<ForgotPassword/>} />
        <Route path="/dashboard" element={<PrivateRoute isAuthenticated={authenticated} redirectPath={"/"}
          component = {Dashboard}/>}/>        
        </Routes>
      </Router>
      
    </div>
  )
}


export default App

該代碼不起作用,因為該組件不斷地重新渲染。 如何更改項目中刷新時的主路由在本地存儲中而不影響應用程序啟動時? 謝謝

您的無限循環可能是由於您在 useEffect 中設置 state 引起的。 你可以在 useEffect 中調用 setState,只要確保你沒有一直這樣做。

  useEffect ( () => {
    if(!authenticated){
    const token: string | null  = localStorage.getItem('token')   
    if (token)
    {
      setAuthenticated(true)
      window.location.assign("/dashboard")
    }
    else{
        /* You can have something here */
     }
    }
  }, [authenticated])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM