首页 > 解决方案 > React 状态被“损坏”

问题描述

我正在开发一个简单的 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了属性,只是又加了两个dispatches来手动设置loading flag

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

标签: javascriptreactjsredux

解决方案


当你这样做

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

您不是在比较下一个和上一个道具。“this.props.advertisers”可能已经设置好了,所以你永远不会进入 setState 行。虽然使用 componentWillReceiveProps 不再是推荐的方式(你可能不需要派生状态),但你可能想要大致做的是:

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

推荐阅读