I am working on a news feed web application and some of my code:
MainContainer.js:
renderContent(source) {
let content;
switch (source) {
case 'bbc':
case 'cnn':
case 'reuters':
content = <Guide source={source}/>;
break;
case 'medium':
content=null;
break;
default:
content = null;
break;
}
return content;
}
render() {
let {source} = this.props;
return this.renderContent(source);
}
This is code from MainContainer,which is a container component to render different news from CNN,or BBC. Its wrapper component is App
App.js render()
<div>
<ScrollableTab sources={sources} handleChange={this.handleSwitchTag.bind(this)} current={current}/>
<MainContainer source={sources[current].toLowerCase()}/>
</div>
When a user click some tab in ScrollableTab,the source property of MainContainer changes,which will lead to a different Guide rendering.(After some logging,source did change in MainContainer).
However,this failed,Guide fail to umount. Only when user clicks Medium in which case renderContent()returns null can Guide umount.
I thought,this probably because React.js cannot distiguish similar components and with some optimization,it thinks there is no need to umount the 'same' component which actually is a different one.
So,I add key= in renderContent,I mean:
renderContent(source) {
let content;
switch (source) {
case 'bbc':
case 'cnn':
case 'reuters':
content = <Guide key={source} source={source}/>;
break;
case 'medium':
content=null;
break;
default:
content = null;
break;
}
return content;
}
render() {
let {source} = this.props;
return this.renderContent(source);
}
In this way, It works. But I cannot find any explanation in documentation of React.js. Or I just missed out some docs.Can someone tell me whether it is a bug or just over-optimization?