【问题标题】:Why component update lifecycle executes whenever parent's state changes?为什么每当父级的状态发生变化时,组件更新生命周期就会执行?
【发布时间】:2019-06-22 06:20:47
【问题描述】:

我有一个名为“App”的父组件,其中使用了一个名为“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() 也会执行

【问题讨论】:

    标签: reactjs react-component react-lifecycle


    【解决方案1】:

    父组件被触发重新渲染,在你的NewComp,shouldComponentUpdate总是默认返回true,所以NewComp也被触发重新渲染。您可以通过在NewComp 中实现shouldComponentUpdate 或使用PureComponent 来避免它:

    export default class NewComp extends PureComponent {
    
      componentDidUpdate(){
        console.log('Child component did update');
      }
    
      render() {
        return (
          <div>
            <h1>Child Component</h1>
          </div>
        )
      }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用shouldComponentUpdate 生命周期方法来控制组件何时可以更新。通常componentDidUpdate 在 props 或 state 更新时执行。

      【讨论】:

      • 如你所说,'componentDidUpdate 在 props 或 state 更新时执行',但这里没有 state 或 props 更新
      • shouldComponentUpdate 默认发送 true,因此当父级重新渲染时,子级也会更新,从反应文档中引用“shouldComponentUpdate() 在接收新道具或状态时在渲染之前调用。默认值为 true。初始渲染或使用 forceUpdate() 时不会调用此方法。"
      【解决方案3】:

      您可以看到以下查询。和你的很像

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

      我希望它有所帮助。

      【讨论】:

        【解决方案4】:

        组件Update生命周期钩子是当组件state有更新时应该使用的钩子,当有更新时这些钩子肯定会执行状态更新,这就是它们的目的。

        如果您只想在创建组件时执行某些逻辑,请考虑使用 Creational Lifecycle hooks

        或者

        如果你想使用componentDidUpdate那么,请检查你想要的state或prop值是否改变然后继续

        创意生命周期挂钩:

        更新生命周期挂钩:

        【讨论】:

          猜你喜欢
          • 2017-04-06
          • 1970-01-01
          • 2021-07-09
          • 2022-07-06
          • 2020-03-19
          • 2013-05-31
          • 2015-07-29
          • 2021-10-06
          • 2017-10-24
          相关资源
          最近更新 更多