【问题标题】:How do I display my API information onto React Component?如何在 React 组件上显示我的 API 信息?
【发布时间】:2018-06-06 05:10:12
【问题描述】:

我一直试图让 Star Wars API 在我的应用程序上运行,但无济于事。所以我从头开始创建了一个完全空的反应应用程序,专门用于测试我的 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.state.jedi}。您将需要在渲染中循环,因为它是一个数组。还要验证 API 结果中的 data 是否为数组。
  • 您应该循环遍历绝地并返回有效的 HTML。像this.state.jedi.map((val) =>

    anything

    )

标签: javascript reactjs api setstate


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    问题是您正在渲染对象,您应该使用 this.state.jedi.name 或循环通过它来渲染。

    【讨论】:

      猜你喜欢
      • 2020-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多