react子组件接收的props赋值给state的陷阱问题
react子组件接收的props赋值给state的陷阱
一般情况下,子组件接收到父组件传来的props
当做变量直接用就可以,但是个别情况下子组件需要将props赋值给state。
一开始,按照常规写法
class Child extends React.Component {
constructor(props) {
super(props)
this.state = {
list: props.list
}
}
}会发现,页面会重新渲染,但是页面数据并没有变化。
这涉及到要熟悉react的生命周期(图片来自于jianshu.com/p/b331d0e4b398,深表感谢)

当父组件更新导致子组件更新时
子组件的生命周期执行顺序是
componentWillReceiveProps --> shouldComponentUpdate --> componentWillUpdate --> render --> componentDidUpdate
也就是说子组件刷新的时候,不再执行constructor
当然也就不会对state重新赋值,所以子组件虽然执行了render,但是渲染数据不变。
解决此问题并不难
就是在componentWillReceiveProps中重新对state赋值,即可。
componentWillReceiveProps(props) {
this.setState({
list: props.list
})
}只有类组件有此问题,函数组件没有此问题。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
React Hooks之使用useCallback和useMemo进行性能优化方式
这篇文章主要介绍了React Hooks之使用useCallback和useMemo进行性能优化方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-06-06
React报错之Parameter event implicitly has a
这篇文章主要为大家介绍了React报错之Parameter event implicitly has an any type,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-08-08


最新评论