我有一个包含三个组件的搜索页面。浏览主题组件列出了可供选择的主题。浏览文章组件根据主题ID列出所有文章,如果没有主题ID,则加载所有文章。 home组件包含browsetopics和browsearticles组件,并根据单击的主题更改其状态。
class BrowseTopics extends React.Component {
constructor(props) {
super(props);
this.topicSelect = this.topicSelect.bind(this);
this.state = {error: "", topics: []};
}
componentDidMount(){
// API call which updates state topics with the list of topics
}
topicSelect(id,e) {
e.preventDefault();
this.props.topicChange(id);
}
render () {
// Rendering list of topics from API and nothing if request has not been sent
}
}
class BrowseArticles extends React.Component {
constructor(props) {
super(props);
this.state = {error: "", articles: [], url: "/api/articles"};
}
componentDidMount() {
if(this.props.topicId){
var url = '/api/topic/'+this.props.topicId+'/articles';
this.setState({url: url});
}
// Make a request to url and get articles
}
render () {
// Renders the list of articles
}
}
class Home extends React.Component {
constructor(props) {
super(props);
this.handleUpdate = this.handleUpdate.bind(this);
this.state = {topicId: ""};
}
handleUpdate(topicId) {
this.setState({topicId: topicId});
}
render () {
return(
<div>
<BrowseTopics user={this.props.user} topicChange={this.handleUpdate}/>
<BrowseArticles user={this.props.user} topicId={this.state.topicId}/>
</div>
);
}
}
我需要的是,我希望browseTopics组件停止在父状态更改上重新渲染。 我尝试使用shouldComponentUpdate()(返回false),但这甚至会停止componentDidMount()部分,并且列表不会被填充。
一旦对API进行请求并呈现组件,我希望所有进一步重新呈现的browseTopics都停止让排序正常运行。
答案 0 :(得分:10)
来自docs:
如果
shouldComponentUpdate()
返回false,则不会调用componentWillUpdate()
,render()
和componentDidUpdate()
我可能想设置某种标志告诉我的BrowseTopics
组件已经发出了API请求,我不再需要/希望组件更新:
class BrowseTopics extends React.Component {
constructor(props) {
super(props);
this.topicSelect = this.topicSelect.bind(this);
this.state = {
error: "",
topics: [],
hasFetched: false // flag for API
};
}
componentDidMount(){
// API call which updates state topics with the list of topics
fetch( 'myapi.json' )
.then( res => {
// set flag denoting API results have been fetcehd
this.setState({
hasFetched: true,
topics: <your topics>
});
})
}
shouldComponentUpdate(nextProps, nextState) {
if ( this.state.hasFetched ) {
return false;
}
return true;
}
...