Stop rendering of a component after componentDidMount()

后端 未结 1 1235
無奈伤痛
無奈伤痛 2020-12-09 14:03

I have a search page with three components. The browse topics component lists the topics to choose from. The browse articles component lists all the articles based on the to

相关标签:
1条回答
  • 2020-12-09 14:06

    From docs:

    if shouldComponentUpdate() returns false, then componentWillUpdate(), render(), and componentDidUpdate() will not be invoked

    I'd probably want to set some sort of flag telling my BrowseTopics component that the API request has been made and I no longer need/want the component to update:

    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;
      }
      ...
    
    0 讨论(0)
提交回复
热议问题