如何在 React Component 上显示我的 API 信息?

How do I display my API information onto React Component?

我一直在尝试在我的应用程序中获取星球大战 API 运行,但无济于事。因此,我从头开始创建了一个完全空的 React 应用程序,仅用于测试我的 API。 我将状态设置为空数组,然后获取 api 并将状态设置为等于 json 数据。控制台记录 api 数据工作正常,我能够看到显示的所有对象,但是将其设置为状态会破坏事情。 早些时候我试图遍历这些对象,但它似乎没有用。

到目前为止我有这个

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor(){
    super()
    this.state = {
      jedi: []
    }
  }

  componentDidMount(){
    fetch('https://swapi.co/api/people/1/?format=json').then(response => {
      return response.json()})
      .then(data => {
      // Work with JSON data here
      this.setState({jedi: data });
    }).catch(err => {
        console.log(err)
      // Do something for an error here
    });
  };

  render() {

    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
        {this.state.jedi}
        </p>
      </div>
    );
  }
}

export default App;

这是错误:

×
Objects are not valid as a React child (found: object with keys {name, height, mass, hair_color, skin_color, eye_color, birth_year, gender, homeworld, films, species, vehicles, starships, created, edited, url}). If you meant to render a collection of children, use an array instead.
    in p (at App.js:37)
    in div (at App.js:32)
    in App (at index.js:7)

你不能那样放置对象,最简单的方法是使用

this.setState({jedi: JSON.stringify(data) });

问题是您按原样渲染对象,您应该使用 this.state.jedi.name 或循环遍历它来渲染。