React 16.4 ComponentDidMount不遵守严格的相等性检查

时间:2018-09-26 14:20:56

标签: javascript reactjs

问题

你好,我在使用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

2 个答案:

答案 0 :(得分:2)

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

因此,您应确保可以访问密钥的值。

最好的方法是:

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

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

要恢复,问题出在您的if condition上,而问题也出在undefined而非"undefined"上,因为如果您进行比较

undefined === "undefined" --> false 

答案 1 :(得分:1)

添加以下条件

  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 );
 }