React Router保持渲染错误页面

时间:2018-09-16 08:55:53

标签: reactjs react-redux react-router

整个周末都来过。页面刷新后,React Router会继续先路由到/ login页面,然后再路由到首页“ /”。

ReactDOM.render(
<Provider store={store}>
    <Router>
        <Switch>
        <Route path="/login" component={Login} />
            <AuthenticatedComponent>
            <Header />
            <Route path="/" component={App} exact />
            </AuthenticatedComponent>
        </Switch>
    </Router>
</Provider>,
document.getElementById("root")
);

我尝试绕过路线,但这没有用-没有错误,它只是做同样的事情。我正在做的一件事是说。 “如果用户已登录(不为null),请立即将其路由到首页“ /”。这是在{登录}组件中完成的,并写在下面:

componentWillReceiveProps(props) {
    if(props.user !== null) {
        props.history.push('/')
    }
}

这就像一个护身符。问题是,每当我刷新浏览器时,URL都会立即转到/ login,然后转到“ /”(即主页)。我添加了AuthenticatedComponent包装器作为最后的测试。我在此组件中编写了以下内容:

componentWillMount(){
    if( this.props.user !== null) {
        this.props.history.push('/')
    } else {
        this.props.history.push('/login')
    }
}

我没有收到任何错误-该功能刚刚出现

1 个答案:

答案 0 :(得分:1)

<Switch>包住<AuthenticatedComponent>(并将<Header />移到auth组件中)。

或创建一个HOC Wrapper component(如果某些路由需要auth,而有些则不需要auth,则是模块化的和有用的)。

工作示例:https://codesandbox.io/s/5m2690nn6n

RequireAuth.js

import React, { Component, Fragment } from "react";
import { withRouter } from "react-router";
import Login from "./Login";
import Header from "./Header";

class RequireAuth extends Component {
  state = { isAuthenticated: false };

  componentDidUpdate = (prevProps, prevState) => {
    if (this.props.location.pathname !== prevProps.location.pathname && !this.state.isAuthenticated) {
      this.props.history.push("/");
    }
  };

  isAuthed = () => this.setState({ isAuthenticated: true });

  unAuth = () => this.setState({ isAuthenticated: false });

  render = () => (
    !this.state.isAuthenticated 
      ? <Login isAuthed={this.isAuthed} />
      : <Fragment>
          <Header unAuth={this.unAuth} />
          {this.props.children}
        </Fragment>
  );
}

export default withRouter(RequireAuth);

index.js

import React from "react";
import { render } from "react-dom";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import Home from "../components/Home";
import Players from "../components/Players";
import Schedule from "../components/Schedule";
import RequireAuth from "./components/RequireAuth";
import "uikit/dist/css/uikit.min.css";

render(
  <BrowserRouter>
    <RequireAuth>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/players" component={Players} />
        <Route path="/schedule" component={Schedule} />
      </Switch>
    </RequireAuth>
  </BrowserRouter>,
  document.getElementById("root")
);

对于任何使用react-router v3的人:

index.js

render (
  <Router>
    <Route path="/" component={RequireAuth}>
      <IndexRoute component={Home} />
      <Route path="players" component={Players} />
      <Route path="schedule" component={Schedule} />
    </Route>
  </Router>, document.getElementById("root")
);