假设我在 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
更改的props,React 会尝试重新渲染它吗?如果我有 1000 个这样的孩子,等等怎么办?
我担心的是一种情况,我有一个非常深的ChildComponent
包含子孙组件的庞大树,但我只想对ParentComponent
. 有没有办法让 React 只更新父级,而不尝试重新渲染子级?