React,父级渲染会让孩子重新渲染吗?

时间:2016-10-24 12:09:25

标签: reactjs

日志显示我的父组件正在重新渲染 但是子组件的render方法没有被调用。

我认为孩子用以下逻辑重新投降,我认为我错了。 如何在父母重新渲染时决定哪些子组件被重新渲染?

  • 家长的渲染
  • - >孩子的shouldComponentUpdate被称为
  • - > if shouldComponentUpdate返回true,child rerenders

父渲染看起来像

  render() {

    let { viewConfig } = this.props
    console.log("ViewConfigSettingBase rendering")
    return (
      <div>
        {
          Object.keys(viewConfig.availableSubviewConfigMap).map((sectionName, index) => {
            var subviewConfigData = viewConfig.availableSubviewConfigMap[sectionName]
            return (
              <ViewConfigSettingRow
                key={sectionName}
                viewConfigData={subviewConfigData}
                sectionName={sectionName}
                parentViewConfig={viewConfig}
                />
            )
          })
        }
      </div>
    )
  }

1 个答案:

答案 0 :(得分:4)

道具更改进行重新渲染。如果您扩展了PureComponent,孩子们会检查道具是否已更改。如果是 - > shouldComponendUpdate将返回true,否则返回false。也许是这样的?

组件生命周期: https://facebook.github.io/react/docs/react-component.html

<强>更新

  

对道具或州的更改可能会导致更新。在重新渲染组件时,会调用这些方法:

componentWillReceiveProps()  
shouldComponentUpdate()  
componentWillUpdate()  
render()  
componentDidUpdate()  

<强> shouldComponentUpdate()

  

使用shouldComponentUpdate()让React知道组件的输出是否>不受当前状态或道具更改的影响。默认的&gt;行为是在每次状态更改时重新呈现,在绝大多数情况下,您应该依赖于默认行为。

     在正在接收新的props或&gt;状态时,在呈现之前调用

shouldComponentUpdate()。默认为true此方法不会为&gt;初始渲染或使用forceUpdate()时调用。

     

当&gt;状态发生变化时,返回false并不会阻止子组件重新呈现。

     

目前,如果shouldComponentUpdate()返回false,则不会调用&gt; componentWillUpdate(),render()和componentDidUpdate()。请注意,将来React可能会将shouldComponentUpdate()&gt;视为提示而不是严格指令,并且返回false仍可能导致重新呈现组件。

     

如果在分析后确定特定组件的速度很慢,则可以>将其更改为从React.PureComponent继承,该实现具有浅层prop和状态比较的&gt; shouldComponentUpdate()。如果您有信心想要手动编写,可以将this.props&gt;与nextProps进行比较,将this.state与nextState进行比较,并返回false告诉&gt;可以跳过更新更新。

您可以在以下页面找到有关反应渲染过程的一些文档: https://facebook.github.io/react/docs/reconciliation.html https://facebook.github.io/react/docs/optimizing-performance.html

相关问题