React成长路之踩坑路:react-router4路由传参,@react-router4.3.1

一、通过params传参:

  1、在路由表中:

<Route path="/search/:type/:keyword?" component={Search} />

  2、Link处使用:

<Link to={'/detail/' + data.id}>

  3、js处使用

this.props.history.push('/detail/' + id)    //页面跳转
this.props.history.replace('/detail/' + id)   //参数改变重新当前页面渲染

  4、参数获取

console.log(this.props.match.params)

这种方法有两个注意点,与2、3区别:

  11、<Route path="/search/:type(/:keyword)" component={Search} /> //2\3路由的可选参数keyword

    <Route path="/search/:type/:keyword?" component={Search} /> // 4路由可选参数是这样的

  12、this.props.history.push('/detail/' + id) //2/3中可实现页面的反复渲染,在4中就会报错,用该用replace代替

  13、this.props.params //在2/3可获取到传递过来的参数,而在4中会抱undefined的错会,改用this.props.match.params即可

二、通过query传参

  1、Link处使用:

<Link to={{pathname:'/detail/',query:{'id': data.id} }}>

  2、js处引用:

this.props.history.push({pathname:'/search', query:{'type': type,'keyword': value}})

  3、参数获取:

console.log(this.props.location.query) //获取到传递过来的query对象

三、通过state传参

  1、Link处使用

<Link to={{pathname:'/detail/',query:{'id': data.id} }}>

  2、js处引用

this.props.history.push({pathname:'/search', query:{'type': type,'keyword': value}})

  3、参数获取

console.log(this.props.location.state) //获取到传递过来的query对象

注:query与state传参异同点

  同:

  1、不需要配置路由表

  2、必须有其它页面跳转过来才能获取参数,当前页面刷新,参数清空

  异:

  1、state传参是加密的,query是公开的,显示在地址栏