如果子组件的props不变,React是否仍然重新渲染它? [英] If the props for a child component are unchanged, does React still re-render it?
问题描述
假设我在React中有以下父组件和子组件配对:
Suppose I have the following pairing of parent and child components in 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个这样的孩子怎么办?
When I do the forceUpdate
, since none of the props that were passed to the ChildComponent
changed, will React try to re-render it? What if I have 1000 such children, etc?
我担心的是我有一个非常深的 ChildComponent
包含一个完整的后代组件树,但我只想在 ParentComponent
上进行一些相对整齐的更改。有没有办法让React只更新父级,而不尝试重新渲染子级?
What I'm worried about is a situation where I have a very deep ChildComponent
containing a whole massive tree of descendant components, but I only want to enact some relatively cosmetic changes on the ParentComponent
. Is there any way to get React to update only the parent, without trying to re-render the children as well?
推荐答案
React重新渲染 ParentComponent
它会自动重新渲染 ChildComponent
。唯一的解决方法是在 ChildComponent
中实现 shouldComponentUpdate
。你应该比较 this.props.a
, this.props.b
和 this.props .c
和 ChildComponents
自己的状态决定是否重新渲染。如果您使用的是不可变数据,那么您可以使用严格相等比较上一个和下一个状态和道具 ===
。
When React re-renders ParentComponent
it will automatically re-render ChildComponent
. The only way to get around is to implement shouldComponentUpdate
in the ChildComponent
. You should compare this.props.a
, this.props.b
and this.props.c
and ChildComponents
own state to decide to re-render or not. If you are using immutable data than you can just compare previous and next state and props using strict equality ===
.
您的代码有一些注意事项
There are a few thing to note with your code
- 您不需要
forceUpdate
当你setState
时。 React会自动为你做这件事。 -
你可能意味着:
- You dont need to
forceUpdate
when yousetState
. React automatically does it for you. You probably meant:
< ChildComponent a = {this.props.a} b = {this.props.b} c = {this.props.c} />
这篇关于如果子组件的props不变,React是否仍然重新渲染它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!