【发布时间】: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