我有一个包含三个部分的搜索页面。浏览主题组件列出了可供选择的主题。浏览文章组件基于主题ID列出所有文章,如果没有主题ID,则加载所有文章。home组件包含browsertopics和browserarticles组件,并根据所单击的主题更改其状态。
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的请求并呈现了组件后,我希望所有进一步的browserTopics重新呈现都停止,以使排序正常运行。
从文档:
如果shouldComponentUpdate()返回false,那么componentWillUpdate(),render()和componentDidUpdate()将不被调用
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
我可能想要设置某种标志来告诉我的BrowseTopics组件已经发出了API请求,而我不再需要/想要该组件进行更新:
BrowseTopics
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; } ...