React Router在url参数不同的情况下跳转页面不更新解决方案

React Router在url参数不同的情况下跳转页面不更新解决方案

说明

场景如下:

 <Link to={{
   pathname: "/product/intro",
   state: {
           id: item.productCode,
           type: item.productTypeCode
       }
 }} >{item.productName}</Link>

当前页面相同的url参数不同,并不会去重新触发我们的componentDidMount函数。所以导致页面不会更新。

解决方案及思路

此时,我们就需要用到react生命周期中的componentWillReceiveProps函数。

componentWillReceiveProps(nextProps)

  1. 组件初次渲染时不会执行componentWillReceiveProps
  2. 当props发生变化时执行componentWillReceiveProps
  3. 在这个函数里面,旧的属性仍可以通过this.props来获取
  4. 此函数可以作为 reactprop 传入之后, render() 渲染之前更新 state 的机会
  5. 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斤不改名字的男人!!!

发布了3 篇原创文章 · 获赞 13 · 访问量 1206

猜你喜欢

转载自blog.csdn.net/weixin_44272418/article/details/105420967