Ale*_*exZ 9 javascript reactjs react-jsx
假设我在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]
);
Run Code Online (Sandbox Code Playgroud)
当我这样做时forceUpdate
,由于没有传递给ChildComponent
改变的道具,React会尝试重新渲染吗?如果我有1000个这样的孩子怎么办?
我担心的是一种情况,我有一个非常深的ChildComponent
包含整个大量的后代组件树,但我只想在其上制定一些相对美观的变化ParentComponent
.有没有办法让React只更新父级,而不尝试重新渲染子级?
nil*_*gun 13
当React重新渲染时ParentComponent
,它将自动重新渲染ChildComponent
.要解决的唯一途径是实现shouldComponentUpdate
在ChildComponent
.你应该比较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}/>
归档时间: |
|
查看次数: |
10061 次 |
最近记录: |