在 React 中似乎无法从该 API 检索数据
2020-11-01
247
import react from 'react';
export default class App extends react.Component {
state = {
loading: true,
person: null,
}
having difficulty in getting the data to be rendered. data does show on console log but won't display names on react page please help.
如能提供任何帮助,我们将不胜感激,谢谢
2个回答
这是 API 响应:
[{"id":1,"title":"Mr","firstName":"Danny","lastName":"Dyer","dob":"24/07/1977","active":true},{"id":2,"title":"Mr","firstName":"Nicholas","lastName":"Cage","dob":"07/01/1964","active":true},{"id":3,"title":"Miss","firstName":"Emma","lastName":"Watson","dob":"15/04/1990","active":true},{"id":4,"title":"Prof","firstName":"Bryan","lastName":"Cox","dob":"03/03/1968","active":true}]
它是一个对象数组。
data.res[0]
仅在 API 响应是包含
res
属性的
对象
时才有意义,例如
{
"res": [
{"id":1, ...
因此,请将代码从
person: data.res[0]
更改为
person: data[0]
并从
<div>{this.state.person.name.title}</div>
<div>{this.state.person.name.first}</div>
<div>{this.state.person.name.last}</div>
更改为
<div>{this.state.person.title}</div>
<div>{this.state.person.firstName}</div>
<div>{this.state.person.lastName}</div>
以正确导航数据。
(还请确保将
url
括在字符串分隔符
'
或
"
中,而不是
<
>
)
实时代码片段:
class App extends React.Component {
state = {
loading: true,
person: null,
}
componentDidMount() {
const url = 'https://api.jsonbin.io/b/5e9ef690435f5604bb4567dd';
fetch(url)
.then(response => response.json())
.then(data => this.setState({ person: data[0], loading: false }));
}
render() {
return (
<div>
{this.state.loading || !this.state.person ? (
<div>loading...</div>
) : (
<div>
<div>{this.state.person.title}</div>
<div>{this.state.person.firstName}</div>
<div>{this.state.person.lastName}</div>
</div>
)}
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>
CertainPerformance
2020-11-01
实际上,我通过使用 ! {this.state.loading || !this.state.person ? (
2020-11-01