如果子组件的道具不变,React是否仍然重新渲染它?
问题描述:
假设我有在父母子女下列组件配对阵营:如果子组件的道具不变,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
改变了道具,将反应尝试重新使它?如果我有1000个这样的孩子,等等呢?
我担心的是我有一个非常深的ChildComponent
包含一个完整的后代组件树,但我只想对ParentComponent
进行一些相对美观的更改。有没有办法让React只更新父级,而不尝试重新渲染子级?
答
当React重新渲染ParentComponent
时,它会自动重新渲染ChildComponent
。唯一的解决办法是在ChildComponent
中执行shouldComponentUpdate
。您应该比较this.props.a
,this.props.b
和this.props.c
和ChildComponents
自己的状态以决定是否重新渲染。如果您使用的是不可变数据,则只能比较上一个状态和下一个状态以及使用严格等于===
的道具。
有你的代码需要注意一些事情
- 你不需要
forceUpdate
当你setState
。 React会自动为你做。 -
你大概的意思是:
<ChildComponent a={this.props.a} b={this.props.b} c={this.props.c}/>
哇,这正是我一直在寻找!后续问题 - 是否有任何方法来更新父组件,同时仍允许在子节点上执行'shouldComponentUpdate'?目前,当我的Backbone模型发出change事件时,我的ParentComponent执行'forceUpdate'。有什么我可以做的“强制”一个更新,但仍然在儿童上调用'shouldComponentUpdate'? – AlexZ 2015-02-06 08:42:39
[React docs beg to differ](http://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate)。当使用'forceUpdate'时,它说'shouldComponentUpdate'被忽略。 – AlexZ 2015-02-06 09:02:26
'ChildComponentUpdate'在'ChildComponent'上自动调用,你不需要做任何事情。 'forceUpdate'跳过'ParentComponent'的'shouldComponentUpdate'方法。 – nilgun 2015-02-06 09:05:41