我在React中使用了immutable.js.
var BlackBoard = React.createClass({
getInitialState:function() {
return {
source : Immutable.fromJS({
data : ['list1'],
headerName : 'header-Name',
footerName : 'footer-Name'})
}
},
render:function() {
var rows = [];
var data = this.state.source.get('data');
var headerName = this.state.source.get('headerName');
var footerName = this.state.source.get('footerName');
for (var i = 0;i < data.size; i ++){
rows.push(<ListView key = {i} index = {i} name = {data[i]} handleClickIndex = {this.handleClickIndex} />);
}
return (<div>
<Header key = {headerName} headerName = {headerName} />
{rows}
<Footer key = {footerName} footerName = {footerName} />
</div>);
},
handleClickIndex(index){//just update header data in source.
var source = this.state.source.set('headerName','new Header-Name');
this.setState({source : this.state.source});
}
});
var HeaderComponent = React.createClass({
shouldComponentUpdate : function (nextProps,nextState) {
console.log('header component executes shouldComponentUpdate');
return true;
},
render(){
return <div className="Header">{this.props.headerName}</div>
}
});
var FooterComponent = React.createClass({
shouldComponentUpdate: function(nextProps, nextState) {
console.log('footer component executes shouldComponentUpdate');
return true;
},
render(){
return <div className="Footer">{this.props.footerName}</div>
}
});
执行函数'handleClickIndex'时。我使用'source'中的'new Header-Name'更新'headerName'数据。并执行'setState'以重新渲染所有子组件。我的问题是行和页脚组件中的ListView组件的生命周期函数'shouldComponentUpdate'可以执行但不能在Header组件中执行。我认为所有子组件都应该执行函数'shouldComponentUpdate'。我的目标是在函数'shouldComponentUpdate'中使用不可变数据,以避免重新渲染。谢谢!谢谢!