在 componentDidMount() 之后停止渲染组件

IT技术 reactjs react-router
2021-04-03 19:48:25

我有一个包含三个组件的搜索页面。浏览主题组件列出了可供选择的主题。浏览文章组件根据主题 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 停止以使排序正常运行。

1个回答

文档

如果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;
  }
  ...