2 回答

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是 API 響應(yīng):
[{"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}]
它是一個(gè)對(duì)象數(shù)組。僅當(dāng) API 響應(yīng)是包含屬性的對(duì)象data.res[0]時(shí)才有意義,例如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>
正確導(dǎo)航數(shù)據(jù)。
(還要確保將url字符串分隔符'或", not括起來< >)
直播片段:
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>

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
實(shí)際上我用不同的方式做到了!{this.state.loading || !this.state.person ? (
添加回答
舉報(bào)