query与params的页面路径传值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zm_miner/article/details/84563263

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

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

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

猜你喜欢

转载自blog.csdn.net/zm_miner/article/details/84563263