query與params的頁面路徑傳值
阿新 • • 發佈:2018-11-27
先簡單記錄頁面傳值, 還沒完全弄懂其中的原理
先配置路徑跳轉
const SubRoutes = {
prefix: 'parentPath',
subRoutes: [
{
name: '子路由',
path: 'children',
params: ':data', // 這個地方的修改可以是 params: ':id'
},
],
};
export default SubRoutes;
params data傳參
params傳參
跳轉頁面
const data = JSON.stringify({ id: this.id, name: this.name }); // 傳到children中引數的值 this.props.history.push(`/parentPath/children/${data}`);
children.js中
通過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傳參
上面的路徑跳轉配置,
不寫params這個引數
<Link to={{pathname:'/parentPath/children',query:{id:this.id, name: this.name}}}>跳轉到</Link>
在children.js
通過this.location.query.id接收
componentDidMount() {
const loc = this.props.location;
this.id = loc.query.id;
}
發現個問題, 一開始可以取到值, 但是當你在當前頁面進行重新整理的時候, 你會發現並沒有這個值.並且報錯, 會報’載入元件錯誤== TypeError: Cannot read property ‘id’ of undefined
at CatalogDetails.componentWillMount (index.js?c7f7:97)’ 為啥???
打印出來以後會發現沒有query引數了
解決query傳參重新整理頁面獲取資料失敗問題
所以如果想成功就必須使用sessionStorage在一開始進入頁面的時候就儲存下, 那麼在重新整理頁面的時候就可以得到了.
// 獲取路由跳轉後引數
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']));
使用的時候引入getRouteQuery
使用值的時候就是 this.id, this.name
}
### params傳參 id
上面的路徑跳轉配置, 修改成
params: ‘:id’, // 只能接收一位引數
<Link to={`/parentPath/children/${this.id}`}>跳轉到</Link>
在children.js
通過this.props.match.params.id接收
componentDidMount() {
this.id = this.props.match.params.id;
}
以上三種, 第一種是最常用的