React 获取 url 参数 —— this.props.match

在浏览器的地址栏中输入:

localhost:3000/app/knowledgeManagement/modify/STY20171011124209535/3/1507701970070/0/?s=1&f=7


该地址对应的router如下:

localhost:3000/app/knowledgeManagement/modify/:id/:stepId/:randomNum/:isDefault/?s=&f=


打印this.props.match:


   

可以看到 this.props.match 中包含的 url 信息还是非常丰富的,其中

  • history:包含了组件可以使用的各种路由系统的方法,常用的有 push 和 replace,两者都是跳转页面,但是 replace 不会引起页面的刷新,仅仅是改变 url。
  • location:相当于URL 的对象形式表示,通过 search 字段可以获取到 url 中的 query 信息。(这里 state 的含义与 HTML5 history.pushState API 中的 state 对象一样。每个 URL 都会对应一个 state 对象,可以在对象里存储数据,但这个数据却不会出现在 URL 中。实际上,数据被存在了 sessionStorage 中)(参考: 深入理解 react-router 路由系统
  • match:包含了具体的 url 信息,在 params 字段中可以获取到各个路由参数的值。

  通过以上分析,获取 url 中的指定参数就比较方便了:

// 获取 studyNo
this.props.match.match.params.id // STY20171011124209535

// 获取 stepId
this.props.match.match.params.stepId // 3

// 获取 success
const query = this.props.match.location.search // '?s=1&f=7'
const arr = query.split('&') // ['?s=', 'f=7']
const successCount = arr[0].substr(3) // '1'
const failedCount = arr[1].substr(2) // '7'

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React中使用this.props.dispatch调用后端接口,也需要借助redux-thunk中间件来处理异步操作。下面是一个简单的例子: ```javascript // 定义一个异步action creator export const fetchData = () => { return async (dispatch) => { dispatch({ type: 'FETCH_DATA_REQUEST' }); try { const response = await fetch('/api/data'); const data = await response.json(); dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data }); } catch (error) { dispatch({ type: 'FETCH_DATA_FAILURE', payload: error }); } }; } // 在组件中使用dispatch调用异步action creator import { connect } from 'react-redux'; import { fetchData } from './actions'; class MyComponent extends React.Component { componentDidMount() { // 调用异步action creator this.props.dispatch(fetchData()); } render() { // 根据store中的状态渲染组件 const { isLoading, data, error } = this.props; if (isLoading) { return <div>Loading...</div>; } else if (error) { return <div>Error: {error.message}</div>; } else { return ( <div> <ul> {data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> </div> ); } } } const mapStateToProps = state => ({ isLoading: state.isLoading, data: state.data, error: state.error, }); export default connect(mapStateToProps)(MyComponent); ``` 在上面的例子中,fetchData是一个异步action creator,它返回一个函数,这个函数接收一个参数:dispatch。在函数内部,我们可以使用dispatch方法来分发多个同步action,以更新store中的状态。在组件中,我们通过connect函数将store中的状态映射为props属性,然后在componentDidMount中使用this.props.dispatch调用该方法,以触发异步操作。当异步操作完成后,根据store中的状态渲染组件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值