React中关于url中传参的问题

对于React的url传参问题,总是一脸懵逼,记录一下。

比如如下两个路由

/repos/reactjs/react-router
/repos/vue/vue-router
复制代码

我们可以把看作是url中传了两个参数,定义如下:

/repos/:userName/:repoName
复制代码

1、 路由设置

<Route path="/repos/:userName/:repoName" component={Repo}/>
复制代码

2、Link

 <Link to="/repos/reactjs/react-router">React Router</Link>
复制代码

3、参数获取

{this.props.params.repoName}
复制代码

JS 实现路由的跳转

在react-router中,一般有两种方法。

第一种,使用withRouter(),然后将在内部可以获取this.props.router。

第二种,使用this.context.router,不过在使用前必须定义这个类的contextTypes。

1、 withRouter怎么用?

withRouter高阶组件,提供了history让你使用~

import React from "react";
import {withRouter} from "react-router-dom";

class MyComponent extends React.Component {
  ...
  myFunction() {
    this.props.history.push("/some/Path");
  }
  ...
}
export default withRouter(MyComponent);
复制代码

参数获取

{this.props.match.params}
复制代码

2、使用 Context

react-router v4 在 Router 组件中通过Contex暴露了一个router对象~

在子组件中使用Context,我们可以获得router对象,如下面例子~

import React from "react";
import PropTypes from "prop-types";

class MyComponent extends React.Component {
  static contextTypes = {
    router: PropTypes.object
  }
  constructor(props, context) {
    super(props, context);
  }
  ...
  myFunction() {
    this.context.router.history.push("/some/Path");
  }
  ...
}
复制代码

当然,这种方法慎用~尽量不用。因为react不推荐使用contex哦。在未来版本中有可能被抛弃哦。

Ref1: www.jianshu.com/p/97e4af328…

Ref2: www.jianshu.com/p/5796c360e…

Ref3: React Router 使用教程

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值