【问题标题】:Can't get JSON list ReactJS from fetch无法从 fetch 中获取 JSON 列表 ReactJS
【发布时间】:2019-07-09 02:01:07
【问题描述】:

大家好,我正在使用 Star Wars API 在 ReactJS 中进行实验。

我想获得以下形式的人的集合:

{
    "count": 87,
    "next": "https://swapi.co/api/people/?page=2",
    "previous": null,
    "results": [
        {
            "name": "Luke Skywalker",
            "height": "172",
            "mass": "77",
            "hair_color": "blond",
            "skin_color": "fair",
            "eye_color": "blue", ... (continues)

由于我可以获取单个字符,因此我知道获取机制正在工作,但我无法获取结果中的字符列表。

我的应用是这样的:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Character from './Character'
class App extends Component {
  constructor() {
    super()
    this.state = {
      people : {},
      character: {}
    }
    fetch("https://swapi.co/api/people/1")
            .then(response => response.json())
            .then(data => {
                this.setState({
                    character: data
                })
            })

    fetch("https://swapi.co/api/people/")
            .then(response => response.json())
            .then(data => {
                this.setState({
                    people: data
                })
            })
    console.log(this.state.people)
    console.log(this.state.people.results)
  }
  render() {
    return (
      <div className="App">
        <Character
          character = { this.state.character}
        />
      </div>
    );
  }
}

export default App;

我从 console.log 中获取了这些信息(其余的是工作正常的单个字符)。

第一个 console.log 给了我一个(在 firefox webconsole 中)

对象{ }

第二个给我未定义的。

我已经尝试了很多东西,但似乎无法找到如何获取该字符列表..我错过了什么?

【问题讨论】:

  • 必须将console.log()放在异步函数中

标签: javascript json reactjs fetch


【解决方案1】:

你应该利用这个机会来使用 React 钩子。这是未来?

const App = () => {
    // equivalent to the state object in your constructor
    const [people, setPeople] = React.useState({});
    const [character, setCharacter] = React.useState({});

    // as second argument is an empty array it is
    // the equivalent of componentDidMount
    React.useEffect(() => {
       fetch("https://swapi.co/api/people/1")
         .then(response => response.json())
         .then(data => {
             setCharacter(data);
          }
        )

        fetch("https://swapi.co/api/people/")
          .then(response => response.json())
          .then(data => {
            setPeople(data);
          }
        )
    }, []);

    return (
      <div className="App">
        <Character character={character} />
      </div>
    )
}

【讨论】:

  • JFYI:Hooks 仅适用于功能组件且仅适用于 React >=16.7
  • 该信息不是为您提供的,而是为其他阅读您答案的人提供的。挂钩在 16.8 中是稳定的,但在 16.7 中在功能标志后面实现。
【解决方案2】:

1) 您应该将您的请求调用移至 componentDidMount 生命周期方法

2) setState 方法是异步的,因此记录该值可能不会在那个确切时刻给出正确的值。要获取正确的属性值,请使用第二个参数(一个函数),该参数将在状态更新后调用。

class App extends Component {
  constructor() {
    super()
    this.state = {
      people : [], // it should an array
      character: {}
    }
  }

  componentDidMount() {
    fetch("https://swapi.co/api/people/1")
            .then(response => response.json())
            .then(data => {
                this.setState({
                    character: data
                }, () => console.log(this.state.character))

            })

    fetch("https://swapi.co/api/people/")
            .then(response => response.json())
            .then(data => {
                this.setState({
                    people: data.results
                }, () => console.log(this.state.people.results))

            })

  }

  render() {
    return (
      <div className="App">
        <Character
          character = { this.state.character}
        />
      </div>
    );
  }
}

export default App;

【讨论】:

    猜你喜欢
    • 2019-06-16
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 2017-04-30
    • 2020-05-31
    • 2018-06-05
    • 2021-09-30
    • 1970-01-01
    相关资源
    最近更新 更多