React成長路之踩坑路:react-router4路由傳參(@react-router4.3.1)
阿新 • • 發佈:2018-11-27
在[email protected]中傳參有三種方式
一、通過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是公開的,顯示在位址列