簡體   English   中英

React 私有路由組件呈現兩次

[英]React private route component renders twice

我正在編寫一個 React/firebase 應用程序,我正在嘗試讓一些私有路由工作。 我使用react-firebase-hooks/auth {useAuthState} react-firebase-hooks/auth {useAuthState}來幫助我進行身份驗證。

應用程序:

let App = () => {
  const [user] = useAuthState(auth);
  return (
   <Navbar
      ...
      <a href="/user" />user</a>
      ...
   />
   <Router>
       <div className='main-content'>
       <Route path='/auth/signin' component={Login} />
       <ProtectedRoute path='/user' component={UserHome} 
        isAuth={user} />
   ..
  };

保護路線:

const ProtectedRoute = ({ component: Component, isAuth, ...rest }) => {
  return (
    <Route
      {...rest}
      render={(props) =>
        isAuth ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{ pathname: "/user/signin", state: { from: props.location } }}
          />
        )
      }
    />
  );
};

export default ProtectedRoute;

但是 React 會持續渲染組件兩次,並且在第一次渲染時,props 為 null,這會觸發受保護的路由重定向。 但是在第二次渲染時,道具都在那里,但是為時已晚,並且發生了重定向。

是否可以在渲染或重定向之前等待所有道具加載? 或者有沒有其他方法可以解決這個問題?

此致

由於useAuthState可能需要一段時間來獲取用戶的信息,您應該使用它提供的loading prop 等待它完成:

let App = () => {
  const [user, loading, error] = useAuthState(auth);
  if (loading) {
    return (
      <div>
        <p>Initialising User...</p>
      </div>
    );
  }
  if (error) {
    return (
      <div>
        <p>Error: {error}</p>
      </div>
    );
  }
  return (
    <Navbar
      ...
      <a href="/user" />user</a>
      ...
    />
    <Router>
       <div className='main-content'>
       <Route path='/auth/signin' component={Login} />
       <ProtectedRoute path='/user' component={UserHome} 
        isAuth={user} />
    ..
  };

你可以在這里閱讀更多

暫無
暫無

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

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