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,深表感谢)

react 子组件接收的props赋值给state的陷阱_第1张图片

当父组件更新导致子组件更新时,子组件的生命周期执行顺序是

componentWillReceiveProps --> shouldComponentUpdate --> componentWillUpdate --> render --> componentDidUpdate

也就是说子组件刷新的时候,不再执行constructor,当然也就不会对state重新赋值,所以子组件虽然执行了render,但是渲染数据不变。

所以要解决此问题也并不难,就是在componentWillReceiveProps中重新对state赋值,即可。

componentWillReceiveProps(props) {
    this.setState({
      list: props.list
    })
}

只有类组件有此问题,函数组件没有此问题。

你可能感兴趣的:(react,react)