簡體   English   中英

當 componentShouldUpdate 返回 true 時,為什么我的 React 組件不會重新渲染?

[英]Why won't my react component re-render when componentShouldUpdate returns true?

我無法理解生命周期掛鈎如何在我的 React 應用程序中工作。 我有一個應用程序,我在我的渲染方法中將一些道具傳遞給我的 Pagination 組件,如下所示:

<Pagination
  totalRecords={this.state.blogPosts.length}
  pageLimit={5}
  pageNeighbours={2}
  onPageChanged={() => {console.log('page changed');}}
/>

在分頁構造函數中,我打印出 prop 值。

const { totalRecords = null, pageLimit = 30, pageNeighbours = 0 } = props;
console.log('totalRecords=', totalRecords); 

它打印出 0。

公平地說,我還沒有獲取我的博客文章。 所以在 componentDidMount 中,我像這樣獲取博客文章:

componentDidMount() {
  axios.get('/blogs').then(
    response => {
      if (response.data) {
        const entries = Object.entries(response.data);
        this.setState({ 
          blogPosts: entries.map(p => Object.assign({id: p[0]}, {...p[1]}))
            .sort((p1, p2) => p1.updatedAt > p2.updatedAt ? -1 : 1),
        });
      }
    },
    err => {
      console.log('err=', err);
    });
}

所以現在博客文章被填充,但分頁組件沒有更新(即使博客本身似乎更新)。

這是我需要一些關於 React 生命周期鈎子如何工作的指導的地方。 狀態改變后渲染方法不重新運行嗎? 我希望 Pagination 組件重新渲染,這次有 totalRecords 屬性打印出 3(或某個大於 0 的數字)。 即使重新渲染,構造函數是否只運行一次?

因此,以防萬一我必須觸發重新渲染,我在componentShouldUpdate()方法中運行了它:

shouldComponentUpdate(nextProps, nextState) {
  console.log('this.state.blogPosts.length=', this.state.blogPosts.length);
  console.log('nextState.blogPosts.length=', nextState.blogPosts.length);
  return this.state.blogPosts.length !== nextState.blogPosts.length;
}

實際上, this.state.blogPosts.length顯示0nextState.blogPosts.length顯示3 所以它們是不同的,我期待 state 更新 3 篇博文。 如果長度不同,我會返回 true,它們是,所以組件應該更新。 這不意味着重新渲染嗎?

無論如何,totalRecords 仍然是 0。我什至在 Pagination 組件中設置了一個時間間隔:

setInterval(() => {
  console.log('this.totalRecords =', this.totalRecords);
}, 5000);

在博客文章被獲取並添加到狀態很久之后,它每五秒打印一次 0...。

為什么分頁組件不使用 totalRecords 的新值更新?

也許你忘了使用componentWillReceivePropsPagination組件。

componentWillReceiveProps(nextProps) {
  this.setState({ totalRecords: nextProps.totalRecords })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM