简体   繁体   English

React 私有路由组件呈现两次

[英]React private route component renders twice

Im writing an React/firebase app and I'm trying to get some private routes to work.我正在编写一个 React/firebase 应用程序,我正在尝试让一些私有路由工作。 Im using {useAuthState} from react-firebase-hooks/auth to help me authenticate.我使用react-firebase-hooks/auth {useAuthState} react-firebase-hooks/auth {useAuthState}来帮助我进行身份验证。

App:应用程序:

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} />
   ..
  };

Protected route:保护路线:

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;

But react keeps rendering the components twice, and at the first render the props are null which triggers the protected route to Redirect.但是 React 会持续渲染组件两次,并且在第一次渲染时,props 为 null,这会触发受保护的路由重定向。 But on second render the props are all there but then it's to late and the redirect has occurred.但是在第二次渲染时,道具都在那里,但是为时已晚,并且发生了重定向。

Is it possible to wait for all the props to load before render or redirect?是否可以在渲染或重定向之前等待所有道具加载? Or is there any other way to solve this?或者有没有其他方法可以解决这个问题?

Best regards此致

Since useAuthState may take a while to fetch the information of the user, you should use the loading prop that it provides to wait for it to finish:由于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} />
    ..
  };

You can read more here你可以在这里阅读更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM