首页 技术 正文
技术 2022年11月12日
0 收藏 871 点赞 3,509 浏览 1479 个字

今天发现, 当使用react-router(v4.2.2)时,路由需要传入参数, 但是如果路由跳转时,url仅仅改变的是参数部分,如从hello/1跳转到hello/2,此时虽然参数更新了,但是页面是不会更新的,这也算是react-router的一个设计缺陷吧发现网上的解决方法主要有两种一、先跳转到一个与当前页面不仅仅是路由参数不同的页面,然后再跳转回来,这样路由跳转了两次。如下所示:

this.props.history.push('/empty'); // 空白页面
setTimeout(() => {
this.props.history.replace(`/hello/${id}`); // 要跳转的页面,其中id为参数
});

但是这样的话白白加载了一个页面,个人感觉不是很好

二、第二种方法是使用 componentWillReceiveProps(newProps) 函数,当 props 改变时,我们就可以在该函数中通过 newProps.match.params.id 拿到新的url参数,进而进行更新。如下

componentWillReceiveProps(newProps) {
const id = newProps.match.params.id;
// 一些操作
}

我个人比较喜欢这种方法但是如果使用这种方法的话,需要注意的一点是:我们可能在react中使用的的组件不止一个,需要执行 componentWillReceiveProps 方法的组件可能是作为子组件存在的。也就是说react-router直接作用的组件是使用 componentWillReceiveProps 组件的父组件这个时候路由参数的改变是监测不到的,为了能够监测到,需要在父组件中把 props 传给子组件,就像这样

<Route path="/hello/:id" component={MyHome} />export default class MyHome extends React.Component {
constructor(props) {
super(props);
this.state = {
};
} render() {
return (
// react-router当url参数改变时不能自动更新页面,为了url参数改变时能够自动更新
// 在子组件中使用componentWillReceiveProps(),当props改变时会自动调用该函数
// 但是现在url的参数是直接作用在page(当前页面组件)上的,为了让子组件监测到props
// 的变化,将props全部传给子组件
<UserInfo {...this.props} />
);
}
}export default class UserInfo extends React.Component {
constructor(props) {
super(props);
this.state = {};
} componentWillReceiveProps(newProps) {
const id = newProps.match.params.id;
//一些操作
} render() {
return (
<div className="userinfo-container">
</div>
);
}
}

如有错误,欢迎留言指出


参考:

https://www.cnblogs.com/gdsblog/p/7348375.htmlhttps://segmentfault.com/q/1010000010522122http://www.shenyujie.cc/2018/03/04/reactRouter_v1/

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,494
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,133
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297