【问题标题】:Accessing to properties using dot notation in React throws me an error在 React 中使用点符号访问属性会引发错误
【发布时间】:2018-10-15 02:59:41
【问题描述】:

我正在尝试使用点表示法访问 json 对象,但它会引发错误。这是我的代码:https://codepen.io/manAbl/pen/aGymRg?editors=0110

我正在像这样解构:const { weather } = this.state;

当我这样做时:console.log(weather) 它向我显示了洞 json 对象,很好,但是当我尝试执行 console.log(weather.name) 时,控制台会抛出一个错误

我做错了什么?我一定错过了一些简单的东西,但我看不到它,我被卡住了

我希望能够访问属性并将它们设置为我的状态的值,因此我可以编写一些函数来根据该位置的当前天气情况显示图标

【问题讨论】:

    标签: reactjs object properties fetch


    【解决方案1】:

    你像这样初始化你的状态:

    this.state = {
      weather: null,
      loading: true,
    };
    

    然后您将更新您的componentDidMount 中的weather var

    componentDidMount 在调用render 方法后被触发

    所以第一次调用render 方法时,你的weather 变量是null 并在componentDidMount 被调用后填充

    你应该这样做

    this.state = {
      weather: {},
      loading: true,
    };
    

    或检查您的 var 是否不是 null

    【讨论】:

      【解决方案2】:

      this.state.weather 最初是null (在调用componentDidMount 中的setState 之前),因此在访问属性之前需要先检查它是否不为空。

      或者,最初将weather 设置为{} 而不是null

      【讨论】:

      • ...或通过console.log(weather ? weather.name : "weather is not set")查看
      • 谢谢!问题是因为我试图在 api 调用之前访问属性,所以我得到了 null 并导致了错误
      猜你喜欢
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      相关资源
      最近更新 更多