繁体   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