先簡(jiǎn)單記錄頁(yè)面?zhèn)髦? 還沒(méi)完全弄懂其中的原理
先配置路徑跳轉(zhuǎn)
const SubRoutes = {
prefix: 'parentPath',
subRoutes: [
{
name: '子路由',
path: 'children',
params: ':data', // 這個(gè)地方的修改可以是 params: ':id'
},
],
};
export default SubRoutes;
params data傳參
params傳參
跳轉(zhuǎn)頁(yè)面
const data = JSON.stringify({ id: this.id, name: this.name }); // 傳到children中參數(shù)的值
this.props.history.push(`/parentPath/children/${data}`);
children.js中
通過(guò)this.props.match.params.data接收
componentDidMount() {
const data = JSON.parse(this.props.match.params.data);
this.id = data.id;
this.name = data.name;
}
query傳參
query傳參
上面的路徑跳轉(zhuǎn)配置,
不寫(xiě)params這個(gè)參數(shù)
<Link to={{pathname:'/parentPath/children',query:{id:this.id, name: this.name}}}>跳轉(zhuǎn)到</Link>
在children.js
通過(guò)this.location.query.id接收
componentDidMount() {
const loc = this.props.location;
this.id = loc.query.id;
}

發(fā)現(xiàn)個(gè)問(wèn)題, 一開(kāi)始可以取到值, 但是當(dāng)你在當(dāng)前頁(yè)面進(jìn)行刷新的時(shí)候, 你會(huì)發(fā)現(xiàn)并沒(méi)有這個(gè)值.并且報(bào)錯(cuò), 會(huì)報(bào)'加載組件錯(cuò)誤== TypeError: Cannot read property 'id' of undefined
at CatalogDetails.componentWillMount (index.js?c7f7:97)' 為啥???????
打印出來(lái)以后會(huì)發(fā)現(xiàn)沒(méi)有query參數(shù)了

解決query傳參刷新頁(yè)面獲取數(shù)據(jù)失敗問(wèn)題
所以如果想成功就必須使用sessionStorage在一開(kāi)始進(jìn)入頁(yè)面的時(shí)候就保存下, 那么在刷新頁(yè)面的時(shí)候就可以得到了.
// 獲取路由跳轉(zhuǎn)后參數(shù)
export const getRouteQuery = (location, queryNames) => {
const queries = {};
if (location.query) {
queryNames.forEach((name) => {
queries[name] = location.query[name];
window.sessionStorage[`${location.pathname}/${name}`] = queries[name];
});
} else {
queryNames.forEach((name) => {
queries[name] = window.sessionStorage[`${location.pathname}/${name}`];
});
}
return queries;
};
在獲取的地方, children.js中
componentDidMount() {
Object.assign(this, getRouteQuery(this.props.location, ['id', 'name']));
使用的時(shí)候引入getRouteQuery
使用值的時(shí)候就是 this.id, this.name
}
params傳參 id
上面的路徑跳轉(zhuǎn)配置, 修改成
params: ':id', // 只能接收一位參數(shù)
<Link to={`/parentPath/children/${this.id}`}>跳轉(zhuǎn)到</Link>
在children.js
通過(guò)this.props.match.params.id接收
componentDidMount() {
this.id = this.props.match.params.id;
}
以上三種, 第一種是最常用的