React Router - 身份验证检查呈现空白页面

React Router - Auth check renders blank page

我对 React Router 还很陌生。我正在尝试在应用程序运行时实施身份验证检查,如下所述:。如果登录它应该加载仪表板组件,如果没有你应该被重定向到登录屏幕。

重定向不起作用,它只是一个空白页面。

有什么想法吗?

export default class App extends React.Component {
  state = {
    auth: false
  };

  updateAuth = value => {
    this.setState({
      auth: value
    });
  };

  render() {
    const { auth } = this.state;
    console.log(auth);

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

    return (
      <Router>
        <div>
          <Route path="/login" component={Login} auth={this.updateAuth} />
          <PrivateRoute path="/dashboard" component={Dashboard} />
        </div>
      </Router>
    );
  }
}

https://codesandbox.io/s/rj6pqkw7xq

您仍然将 PrivateRoute 上的 path 属性设置为 /dashboard,如果您转到 https://qlj5rnnlnq.codesandbox.io/dashboard,它将尝试加载您的仪表板页面,但失败,因为文件服务器上没有 .js 文件扩展名。

如果您想从根 URL 转到仪表板页面,请将路径更改为:

<PrivateRoute authed={true} path="/" component={Dashboard} />

同时更改仪表板文件的文件扩展名,使其变为 Dashboard.js