为什么每当父母的状态改变时,组件更新生命周期就会执行?

时间:2019-01-29 07:16:00

标签: reactjs react-component react-lifecycle

我有一个名为“ App”的父组件,其中使用了一个子组件 'NewComp'。我已经在子组件中定义了componentDidUpdate()生命周期,而不是 在父组件中。

父组件:

class App extends Component {

    state = {
      count:0,
    }

    change = () =>{
      this.setState({
        count:this.state.count+1,
      })
    }

    render() {

      return (
        <div>
          <p>Count = {this.state.count}</p>
          <button onClick={this.change}>Add Count</button>
          <NewComp />
        </div>
      );
    }
}

子组件:

export default class NewComp extends Component {

  componentDidUpdate(){
    console.log('Child component did update');
  }

  render() {
    return (
      <div>
        <h1>Child Component</h1>
      </div>
    )
  }
}

现在,每次我通过“添加计数”按钮更改父状态时,即使子组件中没有任何更改,子组件中的componentDidMount()也会执行

4 个答案:

答案 0 :(得分:1)

父组件被触发重新渲染,并且在您的NewComp中,shouldComponentUpdate默认情况下始终返回true,因此NewComp也被触发重新渲染。您可以通过在shouldComponentUpdate中实现NewComp或使用PureComponent来避免这种情况:

export default class NewComp extends PureComponent {

  componentDidUpdate(){
    console.log('Child component did update');
  }

  render() {
    return (
      <div>
        <h1>Child Component</h1>
      </div>
    )
  }
}

答案 1 :(得分:0)

您可以使用shouldComponentUpdate生命周期方法来控制组件何时可以更新。通常componentDidUpdate是在道具或状态更新时执行的。

答案 2 :(得分:0)

您可以看到以下查询。类似于您的

React: Parent component re-renders all children, even those that haven't changed on state change

我希望它会有所帮助。

答案 3 :(得分:0)

Component Update 生命周期挂钩是当组件 state 中有更新时应用于执行某些操作的挂钩,这些挂钩肯定会在存在以下情况时执行状态更新,这就是它们的目的。

  

如果只想在创建组件时执行一些逻辑,请考虑使用 Creation Life Cycle hooks

  

如果您想使用componentDidUpdate,请检查是否更改了所需的状态 prop 值,然后继续

创造生命周期挂钩:

enter image description here

更新生命周期挂钩:

enter image description here