【问题标题】:React 16.4 ComponentDidMount not respecting strict equality checksReact 16.4 ComponentDidMount 不遵守严格的相等检查
【发布时间】:2018-09-26 22:57:53
【问题描述】:

问题

您好,我在使用 ComponentDidMount 时遇到了一点问题。 如果值不是未定义的,我希望执行网络请求,当组件挂载时它将是未定义的,当使用位于location 内部的状态重定向用户时将传递该值,我将传递给组件使用history.push(route, state); 考虑下面的代码,我只发布了有问题的代码,因为其他行与问题无关。 正如您在下面看到的,如果我正在执行相等性检查的数据不是未定义的,我正在发出网络请求,这在用户重定向时确实有效,因为该值存在,因为用户执行了一个调用 history.push(route, state); 的操作传递路由和要传递的所需数据,但是如果用户访问组件而没有首先使用 history.push(route,state) 重定向它,默认情况下它将是未定义的,在这种情况下,我正在检查该值是否已定义,哪个应该执行相等检查并且根本不执行任何操作,而是控制台向我抛出一个错误,指出我的问题逻辑,ComponentDidMount 是否尊重未定义属性的相等检查?

 componentDidMount() {
    this.loadData();
    if (this.props.location.state.editData !== 'undefined') {
        const { asOfDate } = this.props;
        const { editData } = this.props.location.state;
        const { batchName, fileName } = editData;
        this.getFile(asOfDate, fileName, batchName );
    }
  }

这是我遇到的错误

Cannot read property 'editData' of undefined
    at SingleTransactionContainer.componentDidMount

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您正在尝试访问未定义对象中的键。

    所以你应该确保你可以访问你的密钥的值。

    最好的方法是:

    (((this.props || {}).location || {}).state || {}).editData
    

    如果你没有收到你的道具,它将返回undefined

    继续,问题出在你的if conditionundefined 而不是"undefined" 因为如果你比较

    undefined === "undefined" --> false 
    

    【讨论】:

      【解决方案2】:

      添加以下条件

        if (this.props.location && this.props.location.state && this.props.location.state.editData !== 'undefined') {
            const { asOfDate } = this.props;
          const { editData } = this.props.location.state;
          const { batchName, fileName } = editData;
          this.getFile(asOfDate, fileName, batchName );
       }
      

      【讨论】:

      • 对不起,我没听懂
      猜你喜欢
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      • 2014-11-12
      • 2021-03-24
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 2023-03-07
      相关资源
      最近更新 更多