不确定如何使用react-router v4实现history.push

时间:2017-12-27 23:12:46

标签: reactjs react-router-v4

我正在使用react-router v4并且不确定如何使用history.push将用户推送到新路由,并且已经在我的路由中使用重定向来实现相同的结果。

我想在我的logInAndPush()组件中使用LoginPage方法将新登录的用户推送到/private_page路由,而不是使用{{1}内的重定向逻辑路线。我尝试了使用/login_pagewithRouter的方法,但没有成功。

(仅供参考,以下代码可以粘贴到安装了history的{​​{1}}应用的App.js

create-react-app

1 个答案:

答案 0 :(得分:1)

如果您将道具传播到登录页面,您将可以访问react-routers历史记录。然后,您可以使用它来推送新路线。

import React, { Component } from 'react';
import { BrowserRouter, Link, Redirect, Route, Switch } from 'react-router-dom';
import './App.css';

class App extends Component {
  state = { loggedIn: false };
  logIn = () => { this.setState({ loggedIn: true }); };
  logOut = () => { this.setState({ loggedIn: false }); };
  render() { return <Home loggedIn={this.state.loggedIn} logIn={this.logIn} logOut={this.logOut} />; }
}

const Home = ({ loggedIn, logIn, logOut }) => (
  <BrowserRouter>
    <div style={{ padding: 50 }}>
      <h2>Routing with React-Router</h2>
      <hr /><Navigation loggedIn={loggedIn} logOut={logOut} /><hr />
      <Switch>
        <Route
          path="/private_page"
          render={() => (
            loggedIn === true ? (
              <PrivatePage />
            ) : (
              <Redirect to="/login_page" />
            )
          )}
        />
        <Route path="/public_page" component={PublicPage} />
        <Route
          path="/login_page"
          render={(props) => (
            loggedIn === false ? (
              <LoginPage logIn={logIn} {...props} />
            ) : (
              <Redirect to="/private_page" />
            )
          )}
        />
        <Route exact path="/" render={() => <Redirect to="/public_page" />}/>
      </Switch>
    </div>
  </BrowserRouter>
);

const PrivatePage = () => <h4>This Is The Private Page</h4>;

const PublicPage = () => <h4>This Is The Public Page</h4>;

const LoginPage = ({ logIn, history }) => {
  const logInAndPush = async () => {
    await logIn();
    history.push('/private_page')
    // push user to /private_page
  }
  return (
    <div>
      <h4>Click on button to logIn</h4>
      <button onClick={logInAndPush}>logIn</button>
    </div>
  );
};

const Navigation = ({ loggedIn, logOut }) => {
  const logInLink = loggedIn ? (
    <button onClick={logOut}>logOut</button>
  ) : (
    <Link to="/login_page">Login Page</Link>
  );

  return (
    <nav>
      <Link to="/private_page">Private Page</Link><br />
      <Link to="/public_page">Public Page</Link><br />
      {logInLink}
    </nav>
  );
};

export default App;