大家好,我正在使用 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 中)
Object { }
第二个给我未定义。
我已经尝试了很多东西,但似乎找不到如何获取该字符列表..我错过了什么?
最佳答案
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;
关于javascript - 无法从 fetch 获取 JSON 列表 ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54700639/