gpt4 book ai didi

javascript - 如果子组件的 props 没有改变,React 还会重新渲染它吗?

转载 作者:数据小太阳 更新时间:2023-10-29 03:48:32 26 4
gpt4 key购买 nike

假设我在 React 中有以下父子组件对:

var ChildComponent = React.createClass({
getDefaultProps: function(){
return {
a: 'a',
b: 'b',
c: 'c'
}
},

render: function() {
return (
/* jshint ignore:start */
<div className={'child' + (this.props.b ? ' modifierClass' : '')} something={this.props.a}>
{this.props.c}
</div>
/* jshint ignore:end */
);
}
});


var ParentComponent = React.createClass({
componentDidMount: function(){
//After 10 seconds, change a property that DOES NOT affect the child component, and force an update
setTimeout(function(){
this.setState({foo: 'quux'});
this.forceUpdate();
}.bind(this), 10000);
}

getInitialState: function(){
return {
foo: 'bar',
a: 1,
b: 2,
c: 3
}
},

render: function() {
return (
/* jshint ignore:start */
<div className="parent">
<ChildComponent a={this.props.a} b={this.props.b} c={this.props.c}/>
</div>
/* jshint ignore:end */
);
}
});


React.render(
/* jshint ignore:start */
<ParentComponent />,
/* jshint ignore:end */
document.getElementsByTagName('body')[0]
);

当我执行 forceUpdate 时,由于传递给 ChildComponent 的属性都没有改变,React 会尝试重新渲染它吗?如果我有 1000 个这样的 child 会怎么样?

我担心的是这样一种情况,我有一个非常深的 ChildComponent 包含一整棵庞大的后代组件树,但我只想对 进行一些相对美观的更改父组件。有什么方法可以让 React 只更新父级,而无需尝试重​​新渲染子级?

最佳答案

当 React 重新渲染时 ParentComponent它会自动重新渲染 ChildComponent .解决问题的唯一方法是实现 shouldComponentUpdateChildComponent .你应该比较this.props.a , this.props.bthis.props.cChildComponents自己的状态来决定是否重新渲染。如果您使用的是不可变数据,那么您可以使用严格相等来比较前后状态和 Prop === .

你的代码有几点需要注意

  1. 你不需要 forceUpdate当你setState . React 会自动为您完成。
  2. 你的意思可能是:

    <ChildComponent a={this.props.a} b={this.props.b} c={this.props.c}/>

关于javascript - 如果子组件的 props 没有改变,React 还会重新渲染它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28361252/

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