【问题标题】:Does passing objects as props interfere with componentWillReceiveProps?将对象作为道具传递是否会干扰 componentWillReceiveProps?
【发布时间】:2018-04-01 23:46:32
【问题描述】:

我的 React 应用程序需要使用动态键来跟踪配置对象,所以我将它传递给这样的组件:

<Component configuration={this.state.configuration}>

虽然这有效,但当我在组件的componentWillReceiveProps(nextProps) 中时,我无法辨别配置更改,因为this.props 已经更新为nextProps

如果这不是一个已知问题,也许它与我处理父级配置状态更新的方式有关?以下是我更新配置状态的方法:

  handleConfigurationChangeForKey(newOption, key) {
    const configObject = this.state.configuration;
    configObject[key] = newOption;
    this.setState({configuration: configObject});
  }

提前感谢您的帮助。

【问题讨论】:

    标签: reactjs state setstate


    【解决方案1】:

    我无法辨别配置更改,因为 this.props 已更新为 nextProps。

    这不是真的。 this.props 将拥有当前的道具,nextProps 将拥有即将到来的道具。

    您设置状态的方式可能是问题所在。尝试使用Object.create 或深拷贝功能(如lodash 提供的功能)创建一个新的配置对象。

    const newConfig = Object.create(oldConfig)
    # or
    const newConfig = _.cloneDeep(oldConfig)
    
    newConfig[key] = newValue
    

    这样,对象不会通过引用旧版本而相等。如果复制带来性能问题,您可以尝试为您的状态对象使用Immutable.js 库。

    【讨论】:

      【解决方案2】:

      当您更新配置对象时,您正在改变它:您无法区分nextProps.configurationthis.props.configuration,因为它们是同一个对象。

      解决这个问题的方法基本上是克隆原始配置对象,改变 that,然后使用 setState 使配置指向那个新对象。

      handleConfigurationChangeForKey(newOption, key) {
        const nextConfiguration = {
          ...this.state.configuration,
          [key]: newOption
        };
        this.setState({ configuration: nextConfiguration });
      }
      

      仅使用较旧的语言功能

      handleConfigurationChangeForKey(newOption, key) {
        var nextConfiguration = {};
        nextConfiguration[key] = newOption;
        nextConfiguration = Object.assign(
          {},
          this.state.configuration,
          nextConfiguration
        );
        this.setState({ configuration: nextConfiguration });
      }
      

      【讨论】:

      • 很好的答案,感谢您向我展示如何使用新的传播运算符。
      猜你喜欢
      • 2021-07-12
      • 2017-07-22
      • 2015-01-16
      • 2018-02-12
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      相关资源
      最近更新 更多