gpt4 book ai didi

reactjs - React,父级渲染是否会使子级重新渲染?

转载 作者:行者123 更新时间:2023-12-03 13:36:45 24 4
gpt4 key购买 nike

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

我认为 child 会按照以下逻辑重新渲染,但我认为我错了。当父组件重新渲染时,React 如何决定哪些子组件被重新渲染?

  • 父级渲染
  • -> 子级的 shouldComponentUpdate 被调用
  • -> 如果 shouldComponentUpdate 返回 true,则子级重新渲染

父渲染看起来像

  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>
)
}

最佳答案

React 在 propsstate 更改时重新渲染。如果您扩展了 PureComponent,子级将检查 props 是否已更改。如果是 -> shouldComponendUpdate 将返回 true,否则返回 false。也许是这样的?

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

正在更新

An update can be caused by changes to props or state. These methods are >called when a component is being re-rendered:

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

shouldComponentUpdate()

Use shouldComponentUpdate() to let React know if a component's output is >not affected by the current change in state or props. The default >behavior is to re-render on every state change, and in the vast majority >of cases you should rely on the default behavior.

shouldComponentUpdate() is invoked before rendering when new props or >state are being received. Defaults to true This method is not called for >the initial render or when forceUpdate() is used.

Returning false does not prevent child components from re-rendering when >their state changes.

Currently, if shouldComponentUpdate() returns false, then >componentWillUpdate(), render(), and componentDidUpdate() will not be >invoked. Note that in the future React may treat shouldComponentUpdate() >as a hint rather than a strict directive, and returning false may still result in a re-rendering of the component.

If you determine a specific component is slow after profiling, you may >change it to inherit from React.PureComponent which implements >shouldComponentUpdate() with a shallow prop and state comparison. If you >are confident you want to write it by hand, you may compare this.props >with nextProps and this.state with nextState and return false to tell >React the update can be skipped.

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

关于reactjs - React,父级渲染是否会使子级重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40218048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com