React

时间:2018-10-24 03:38:42

标签: reactjs routing

我正在尝试使用Create React App 2和React Router 4在React中创建一些受保护的路由。我以Tyler McGinnis的Protected Routes文章为例。这是我的基本应用程序组件。

class App extends Component {
  constructor(props) {
    super(props);

    this.state = { loggedIn: false };
  }

  componentDidMount() {
    console.log('did mount');
    this.setState({ loggedIn: true });
  }

  render() {
    fakeAuth.authenticate(this.state.loggedIn);
    console.log('render');

    return (
      <Router>
        <Fragment>
          <Login />
          <PrivateRoute path="/register" component={Register} />
          <Chordsheets />
          <Chordsheet />
        </Fragment>
      </Router>
    );
  }
}

export default App;

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props => (
    fakeAuth.isAuthenticated === true 
        ? <Component {...props} /> 
        : <Redirect to="/" />
   )}
  />
);

const fakeAuth = {
  isAuthenticated: false,
  authenticate(state) {
    this.isAuthenticated = state;
    console.log('isAuthenticated', this.isAuthenticated);
  }
};

const Login = () => (
  <div>
    <Route exact path="/" component={LoginForm} />
  </div>
);

const Chordsheets = () => (
  <Fragment>
    <Route path="/chordsheets" component={Header} />
    <Route path="/chordsheets" component={AllChordSheets} />
  </Fragment>
);

const Chordsheet = () => (
  <Fragment>
    <Route path="/chordsheet/:id" component={Header} />
    <Route path="/chordsheet/:id" component={ChordSheet} />
  </Fragment>
);

const Header = () => {
  return (
    <header>
      <nav className="links">
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/chordsheets/0">My Chordsheets</Link>
          </li>
        </ul>
      </nav>
    </header>
  );
};

安装组件后,loggedIn设置为true。转到新路线时,不会再次调用渲染,因此无法到达Register路线。

有人对如何组织这个有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

我知道我迟到了,但我很乐意通过查看此 protected-react-routes-generator

来帮助他想要此功能的任何人

您要做的就是以数组的形式提供路由。