代码之家  ›  专栏  ›  技术社区  ›  Moshe Shmukler

反应状态被“破坏”

  •  0
  • Moshe Shmukler  · 技术社区  · 6 年前

    我正在做一个简单的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 财产,例如 活动 它通过 this.props.campaignsLoading 然后做:

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

    现在的问题是,我的状态没有在里面正确设置 组件将接收props() .

    项目正在使用 @rematch 最初我试着 @rematch/loading 当问题发生的时候,以为插件做的不对。然后,我绘制了 加载 手动添加属性,然后再添加两个 dispatch ES手动设置加载 flag .

    所有的道具都被正确地设置/取消设置,但是我的状态没有被设置,没有任何工作。有什么建议吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Gabriel Ferrarini    6 年前

    当你这样做的时候

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

    你不是在比较下一个道具和前一个道具。”“this.props.广告商”可能已经设置好了,所以您永远不会进入设置状态行。尽管使用componentwillreceiveprops不再是推荐的方法( You Probably Don't Need Derived State ),你大概想做的是:

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