【问题标题】:Uncaught TypeError: Can not read property 'name' of null. Returning only true values未捕获的类型错误:无法读取 null 的属性“名称”。只返回真值
【发布时间】:2019-07-11 23:20:42
【问题描述】:

指的是网址https://app.com/api/v1/$ {id}。取决于id,API 返回我的响应 -> null{name: 'a'}。该对象具有“名称”属性。 'name' 属性要设置状态:

this.setState ({
    load: this.props.active ['name']
});

当我单击具有name 属性的项目时,它们会显示在控制台中。当我转到一个返回 'null' 而没有 'name' 属性的元素时。我有错误:Uncaught TypeError: Can not read property 'name' of null

class Details extends Component {
    constructor() {
        super();

        this.state = {
            load: null
        }
    }

  componentDidUpdate(prevProps, prevState) { 
        if(prevProps.active !== this.props.active) {
                this.setState({
                    load: this.props.active['name']
                });
        }
    }

  render () {

    return (
      <div >

      </div>
    )
  } 

我的目标是只返回 true 响应。

类似的东西:

componentDidUpdate(prevProps, prevState) { 

    if (prevProps.active !== this.props.active) {
      let solution = null;
        if(this.props.active) {
          return solution = this.props.active["name"]
        }
        this.setState({
          load: solution
        });
      }

  }

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

    在您的用例中,您可以在组件内检查 this.props.active 是否存在,所以在 render 内...

    if (this.props.active) {
      return (
        <div>Your cool detail view with name attribute.</div>
      );
    } else {
      return (
        <div>Your empty detail view.</div>
      );
    }
    

    但是,如果这些详细视图是某种列表或集合视图的一部分,您可能只想跳过呈现空值的组件。在这种情况下,您应该在上游组件中过滤对象数组 (as described here for example),然后使用过滤后的数组呈现您的集合。

    【讨论】:

      【解决方案2】:

      您可以在 if 语句中将其添加为另一个条件

      if(prevProps.active !== this.props.active && this.props.active !== null) {
      

      【讨论】:

        猜你喜欢
        • 2012-05-31
        • 2022-01-19
        • 2021-12-01
        • 2015-04-30
        • 1970-01-01
        • 1970-01-01
        • 2021-11-18
        相关资源
        最近更新 更多