自定义“ PrivateRoute”组件返回一个React-Router路由||重定向导致不变的违规

时间:2019-02-12 00:47:00

标签: javascript reactjs react-router

我具有以下功能,如React-Router Docs所示,唯一的例外是我正在使用prop传递给组件以检查用户是否已通过身份验证:

const PrivateRoute = ({ component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={(props) => {
        return (
          props.isAuthenticated ? (
            <Component {...props} />
          ) : (
            <Redirect
              to={{
                pathname: '/login',
                state: { from: props.location },
              }}
            />
          )
        );
      }
      }
    />
  );
};

这是正在呈现的内容:

return (
  <React.Fragment>
    { isLoading ? (<SplashScreenView />) : (
      <Router>
        <ContentContext.Provider value={appContent}>
          <TitleBarRouter />
          <Switch>
            <Route exact path="/login" render={props => <LoginView {...props} performAuthentication={this.performAuthentication} isAuthenticating={isAuthenticating} isAuthenticated={isAuthenticated} />} />
            <PrivateRoute exact path="/" render={props => <MainView {...props} checked={appContent.checked} elapsed={elapsed} />} />
            <PrivateRoute exact path="/settings" component={SettingsView} />
            <PrivateRoute exact path="/card" component={CardView} />
            <PrivateRoute exact path="/memberships" component={ActiveMembershipsView} />
          </Switch>
          <TabBarRouter />
        </ContentContext.Provider>
      </Router>
    )}
  </React.Fragment>
);

这就是我设置状态的方式。此功能作为属性传递给/login路由,单击此按钮即会被调用。

  performAuthentication(obj) {
    this.setState({
      isAuthenticating: true,
    }, () => {
      setTimeout(() => {
        this.setState({
          isAuthenticating: false,
          isAuthenticated: true,
        });
      }, 2000);
    });
  }

isAuthenticated设置为true并且应该渲染PrivateRoutes时遇到的错误是Invariant Violation: Maximum update depth exceeded.,我设法将其跟踪到{{ 1}}函数会导致无限循环,而无限循环又应引起错误。我无法为自己的生活弄清楚为什么会这样。我将不胜感激任何指针。

0 个答案:

没有答案