react 子组件接收的props赋值给state--安排上了

一般情况下,子组件接收到父组件传来的props,当做变量直接用就可以,但是个别情况下子组件需要将props赋值给state。一开始,按照常规写法

class Child extends React.Component {
  constructor(props) {
    super(props)
      this.state = {
        list: props.list
      }
    }
}
会发现,页面会重新渲染,但是页面数据并没有变化。

这涉及到要熟悉react的生命周期

 

 

 

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

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

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

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

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

posted on 2022-06-02 16:35  小宇子李  阅读(995)  评论(0编辑  收藏  举报

导航