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

Serena ·
更新时间:2024-09-21
· 505 次阅读

React Router如何在url参数不同的情况下跳转页面不更新解决方案说明解决方案及思路componentWillReceiveProps(nextProps) 说明

场景如下:

{item.productName}

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

解决方案及思路

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

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


作者:月半不是胖~



跳转页面 更新 解决方案 React url

需要 登录 后方可回复, 如果你还没有账号请 注册新账号