反应处理空道具

时间:2018-08-17 14:06:47

标签: javascript reactjs undefined

我要渲染图像,该图像的URL是我在应用程序启动时从API获取的。执行此操作时,会出现以下消息:TypeError: Cannot read property 'icon' of undefined
尽管icon是对象中的属性,但我可以访问其他所有内容,甚至对象。

class Current extends React.Component {
  render() {
    console.log(this.props.current.condition);
    // Ok, first I write undefined to the console, but then the object
    console.log(this.props.current.condition.icon);
    // BAM. Doomsday.

    return (
      // Beneath me everything is totaly fine.
      <div className="Current">
        <div className="Important">
          <div>
            <img src={this} alt={this} />
            <span>{this.props.current.temp_c}</span>
          </div>
          <h1>{this.props.location.name}, {this.props.location.country}</h1>
          <p>{this.props.location.localtime}</p>
        </div>
        <h1>hey</h1>
      </div>
    );
  }
}

export default Current;

我尝试使用ComponentWillMountComponentDiDMount来篡改对象,但这没有帮助。如何在不使应用程序崩溃的情况下访问icon属性?

编辑:对此进行了修正:

<img 
src={typeof(this.props.current.condition) === 'undefined' ? '' : this.props.current.condition.icon} 
alt={typeof(this.props.current.condition) === 'undefined' ? '' : this.props.current.condition.text} 
/>

...但这不是干净的代码,对吧?

3 个答案:

答案 0 :(得分:2)

尝试

src={this.props.current.condition && this.props.current.condition.icon}

答案 1 :(得分:2)

class Current extends React.Component {
  render() {
    const { current } = this.props
    if ( !(current && current.condition) ) return <span>Loading</span>;

    return (
      // Beneath me everything is totaly fine.
      <div className="Current">
        <div className="Important">
          <div>
            <img src={this} alt={this} />
            <span>{this.props.current.temp_c}</span>
          </div>
          <h1>{this.props.location.name}, {this.props.location.country}</h1>
          <p>{this.props.location.localtime}</p>
        </div>
        <h1>hey</h1>
      </div>
    );
  }
}

export default Current;

答案 2 :(得分:0)

测试变量是否未定义的正确方法如下:

this.props.current.condition === undefined

由于typeof()是JavaScript代码中的有效值,因此无需使用undefined

您可以在某种情况下简化此操作,因为undefined已被视为“虚假”。这意味着您可以在undefined语句中直接使用if值。在React中,常见的习惯用法是这样的:

this.props.current.condition && this.props.current.condition.icon

如果undefinedthis.props.current.condition,则此结果将为undefined。否则,它将计算为this.props.current.condition.icon的值。

为了更深入地了解,我建议您学习JavaScript中的“真实性”和“虚假性”。我还建议您了解布尔运算符和短路。

相关问题