react.js - 深对象的状态,异步数据不起作用不起作用、对象、状态、数据

2023-09-11 01:30:28 作者:怀旧的小孩最有噯ミ

我刚刚想出的阵营的状态的对象,有多个孩子不能很容易地呈现。

I've just figured out that object in React's state that have multiple children cannot be rendered easily.

在我的例子我有一个第三方的API通过说话AJAX组件:

In my example I have component which speaks with third-party API through AJAX:

var Component = React.createClass({
  getInitialState: function () {
    return {data: {}};
  },

  loadTrackData: function () {
    api.getDataById(1566285, function (data) {
        this.setState({data: data});
    }.bind(this));
  },

  componentDidMount: function () {
    this.loadTrackData();
  },

  render: function () {
    return (
        <div>
            <h2>{this.state.data.metadata.title}</h2>
        </div>
    );
  }
});

问题是, {this.state.data.metadata} 渲染很好..

{this.state.data.metadata.title} 抛出错误未捕获的类型错误:无法读取的未定义的属性'标题'

什么是正确的方式来处理这种异步数据?

What is the proper way to deal with such async data?

推荐答案

this.state.data.metadata 是未定义加载之前发生。访问对的任何属性未定义为您提供了一个类型错误。这是不特定的反应,它的JavaScript对象引用是如何工作的。

this.state.data.metadata is undefined until loading occurs. Accessing any property on undefined gives you a TypeError. This is not specific to React—it's just how JavaScript object references work.

我建议你使用 {数据:空} 在初始状态,返回别的东西从渲染与条件如如果(!this.state.data)

I suggest you use { data: null } in initial state and return something else from render with a condition like if (!this.state.data).

 
精彩推荐
图片推荐