React-router4实现路由跳转的两种方法

最近在写react的项目,发现React-router4.x和React-router3.x差别挺大的,以下是我项目中实现react路由跳转的两种方法。

安装React-router

在React-router4中,react-router-dom和history是必不可少的。

  • npm install --S react-router
  • npm install --S react-router-dom
  • npm install --S history

配置index.js入口文件

不管是哪一种方法,都不能缺少在index.js入口文件配置路由匹配规则。
1、react-router V4版本丢弃IndexRoute,用exact和Switch替代。
React-router官方文档是使用了IndexRoute(默认路由),但是在v4版本中如果引入IndexRoute是会报错的,因为它被丢弃了,被exact替代了。

exact表示只对当前的路由进行匹配,Switch组件表示独立路由。如果不使用exact和Switch时,会同时渲染’/‘和’/admin’组件,比如这样。
在这里插入图片描述
因此需要将 ‘/admin’ 路由放在 ‘/’ 之前,因为后者包含了前者,但是一旦进入到’/admin’页面,也会渲染’/’。如果使用了exact(不使用Switch)就可以不用关注顺序了。
2、<Router history={history}>的实现效果和<BrowserRouter>一样。<BrowserRouter><HashRouter>的区别是:HashRouter有#

import { Router, Route, BrowserRouter, HashRouter,Switch,Redirect } from "react-router-dom";
import { createBrowserHistory } from "history";
import App from "./pages/MainPageLayout/App";
import Login from "./pages/login/Login";

const history = createBrowserHistory();

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <Switch>
        <Route exact path="/" component={Login}></Route>
        <Route path="/admin" component={App}></Route>
        //重定向
        <Redirect to="/" />
      </Switch>
    </Router>
  </Provider>,
  document.getElementById("root")
);

第一种(推荐)

这种是官网的写法,当继承组件之后,this.props.history.push("/admin");就可以实现页面的跳转

class Login extends Component {
  constructor(props) {
    super(props);
  };
  onFinish = values => {
    this.props.history.push("/admin");
  };

  render() {
    return (
      <div>
        <div className="loginCenter">
          <Form
            {...this.layout}
            name="basic"
            onFinish={this.onFinish}
          >
            <Form.Item {...this.tailLayout}>
              <Button type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }
}
export default withRouter(Login);

第二种

当Login是函数时,如果单单只有history.push("/admin");时,会出现路由发生变化但是页面没有渲染的情况,必须得加上history.go();才会渲染页面。所以我觉得这种方法不太好

const Login = () => {
   const onFinish = values => {
     history.push("/admin");
     history.go();
   };
   return (
       <Form
          {...this.layout}
          onFinish={this.onFinish}
        >
          <Form.Item {...this.tailLayout}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
   );
};
export default withRouter(Login);

PS:如果对我的代码和react项目感兴趣,欢迎clone我的react项目https://github.com/faimi/my-react

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值