React Router如何在url参数不同的情况下跳转页面不更新解决方案
程序员文章站
2024-01-27 18:16:58
...
React Router如何在url参数不同的情况下跳转页面不更新解决方案
说明
场景如下:
<Link to={{
pathname: "/product/intro",
state: {
id: item.productCode,
type: item.productTypeCode
}
}} >{item.productName}</Link>
当前页面相同的url参数不同,并不会去重新触发我们的componentDidMount函数。所以导致页面不会更新。
解决方案及思路
此时,我们就需要用到react生命周期中的componentWillReceiveProps函数。
componentWillReceiveProps(nextProps)
- 组件初次渲染时不会执行componentWillReceiveProps
- 当props发生变化时执行componentWillReceiveProps
- 在这个函数里面,旧的属性仍可以通过this.props来获取
- 此函数可以作为 react 在 prop 传入之后, render() 渲染之前更新 state 的机会
- componentWillReceiveProps的参数为this.props本次改变后的值,而this.props为上次的值
componentWillReceiveProps(nextProps) {
//拿到此时state中传来的id
let id = nextProps.location.state.id;
let url = getProductDetailUrl + "?productCode=" + id;
//开始你的表演!
getJson(url, false, res => {
console.log(typeof (res), 'res')
if (typeof (res) == 'object') {
this.setState({
title: res.productName,
content: res.productDesc,
titleCode: id,
isShow: true,
})
}
else {
this.setState({
isShow: false,
titleCode: id,
})
}
})
}
OK!问题圆满解决!希望可以帮到看到此文的你(▽)。我是胖胖,不瘦回150斤不改名字的男人!!!