React Router-Auth检查呈现空白页

时间:2019-01-03 15:14:41

标签: reactjs react-router-v4

我是React Router的新手。当应用程序按以下答案运行时,我正在尝试执行Auth检查:How to implement authenticated routes in 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

1 个答案:

答案 0 :(得分:2)

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

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

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

还要更改Dashboard文件上的文件扩展名,使其变为Dashboard.js