在react-router@4中傳參有三種方式
一、通過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是公開的,顯示在地址欄