query與params的頁(yè)面?zhèn)髦?/h2>

先簡(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;
}
image.png

發(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ù)了

image.png

解決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;
}

以上三種, 第一種是最常用的

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容