![](/img/trans.png)
[英]React 16.13.1 - child component does not re-render when props change
[英]If the props for a child component are unchanged, does React still re-render it?
假设我在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个这样的孩子怎么办?
我担心的是一种情况,我有一个非常深的ChildComponent
包含一个完整的后代组件树,但我只想在ParentComponent
上进行一些相对美观的更改。 有没有办法让React只更新父级,而不尝试重新渲染子级?
当React重新呈现ParentComponent
,它将自动重新呈现ChildComponent
。 解决方法的唯一方法是在shouldComponentUpdate
中实现ChildComponent
。 您应该比较this.props.a
, this.props.b
和this.props.c
以及ChildComponents
自己的状态来决定是否重新渲染。 如果你使用不可变数据,你可以使用严格相等===
来比较上一个和下一个状态和道具。
您的代码有一些注意事项
setState
时不需要forceUpdate
。 React会自动为您完成。 你可能意味着:
<ChildComponent a={this.props.a} b={this.props.b} c={this.props.c}/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.