如何在 React 中渲染来自 API 响应的数据?

How to render data from API response in React?

如何将 API 的响应初始化为变量,以便我可以在我的 render() 函数中使用它?为什么 component.setState 不起作用? 错误:
未捕获类型错误:无法读取未定义的 属性 'username'(…)

class Main extends React.Component {
 constructor(props) {
     super(props);
    this.state = {
      data: 23
    };
 }

  componentDidMount() {
var component = this;


      fetch('https://fcctop100.herokuapp.com/api/fccusers/top/alltime')
          .then(function(response) {
              return response.json()
          }).then(function(json) {
              var data = json;
              console.log(data[0]);
              console.log(data[0].username);
              component.setState({
                  data: json
              })
          })

  }




  render() {
    return (
      <div>
        <h1>elo{this.state.data[0].username}</h1>


      </div>
    );
  }
}

const docs = document.getElementById('root');

ReactDOM.render( <Main/> , docs);

原因是在第一次渲染时未设置此 "this.state.data[0].username",直到响应从 API 调用返回。

您的渲染方法中类似这样的东西应该可以工作:

render() {
    var someData = this.state.data[0].username || "";
    return (
      <div>
        <h1>elo{someData}</h1>


      </div>
    );
  }