场景如下:
{item.productName}
当前页面相同的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斤不改名字的男人!!!