query与params的页面传值

先简单记录页面传值, 还没完全弄懂其中的原理
先配置路径跳转

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

发现个问题, 一开始可以取到值, 但是当你在当前页面进行刷新的时候, 你会发现并没有这个值.并且报错, 会报'加载组件错误== TypeError: Cannot read property 'id' of undefined
at CatalogDetails.componentWillMount (index.js?c7f7:97)' 为啥???????
打印出来以后会发现没有query参数了

image.png

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

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容