首页 > 解决方案 > React Router - 身份验证检查呈现空白页面

问题描述

我对 React Router 还很陌生。当应用程序运行时,我正在尝试实施身份验证检查:如何在 React Router 4 中实现经过身份验证的路由?. 如果登录它应该加载仪表板组件,如果没有,你应该被重定向到登录屏幕。

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

有任何想法吗?

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

标签: reactjsreact-router-v4

解决方案


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

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

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

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


推荐阅读