反应状态被“破坏”

时间:2018-12-20 06:42:32

标签: javascript reactjs redux

我正在研究一个简单的React.JS前端片段。

我基本上有一个浏览SPA的历史数据。该设计有很多过滤器,我需要一次填充一个过滤器,从我的逻辑层次结构中最顶层的过滤器开始。

我做类似的事情:

  componentWillMount() {
    if (!this.props.advertisers) {
      this.props.loadAdvertisers();
    }
  }

一旦加载了广告商数组,我将其映射到选择组件的选项(使用react-select),将选择项设置为列表中的第一项,然后加载下一个列表-campaigns

据我了解,做到这一点的最佳方法仍然是componentWillReceiveProps(),而且由于componentWillReceiveProps正在逐步淘汰,我有点困惑应该如何做。

我的代码如下:

componentWillReceiveProps(nextProps) {
  if (nextProps.advertisers && !this.props.advertisers) {
    const advertiser = nextProps.advertisers[0];
    this.setState({
      advertiser: {
        value: advertiser['id'],
        label: advertiser['name']
      }
    });
    nextProps.loadCampaigns(advertiser['id']);
  }
  // if campaigns list changed, reload the next filtered array
  if (nextProps.campaigns && this.props.campaigns !== nextProps.campaigns) {
    ...
  }

这很好,直到我决定添加一个加载指示器。我映射了状态的loading属性,例如对于campaigns,它会通过this.props.campaignsLoading公开,然后执行以下操作:

return (this.props.campaignsLoading || this.props...Loading || ...) ? 
       <ProgressIndicator> : <MainContentPanel>

现在的问题是,componentWillReceiveProps()中的状态没有正确设置。

该项目使用的是@rematch,我最初是使用@rematch/loading插件尝试过的,当问题发生时,以为插件做错了。然后,我手动映射了loading属性,并添加了另外两个dispatch来手动设置加载flag

所有道具均已正确设置/取消设置,但是我的状态尚未设置且没有任何效果。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

这样做的时候

if (nextProps.advertisers && !this.props.advertisers) {

您没有比较下一个和上一个道具。可能已经设置了“ this.props.advertisers”,所以您永远不会进入setState行。尽管不再建议使用componentWillReceiveProps(You Probably Don't Need Derived State),但您可能想要做的大致是:

if (nextProps.advertisers && nextProps.advertisers !== !this.props.advertisers) {