![](/img/trans.png)
[英]Error “Cannot read property 'fname' of undefined” in React state
[英]React Error - Cannot read property 'state' of undefined
我正在按照本教程使用提取功能; 我能夠使用以下模擬API提取照片: https : //randomuser.me/api/ ...但是修改了代碼以從API提取其他數據,例如名字。 但是,在處理過程中遇到錯誤:
這是代碼:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(){
super();
this.state = {
pictures: [],
people: [],
};
}
componentWillMount()
{
fetch('https://randomuser.me/api/?results=10')
.then(results => results.json())
.then(data => this.setState({ pictures: data.results }))
.then(data => this.setState({ people: data.results }));
}
render() {
console.log(this.state);
return (
<div>
{
this.state.pictures.map( pic =>(<div><img src={pic.picture.medium} /></div>) ).
this.state.people.map(person => (<div>{person.name.first}</div>))
}
</div>
);
}
}
export default App;
基本上,我試圖弄清楚如何拉出更多圖片,而不是圖片(API中的其他數據),並且不確定我是否走對了軌道。 目前,我正在嘗試獲得名字。 請給我一些幫助嗎?
每個表達式都應用{}
括起來。
{this.state.pictures.map(pic => (
<div>
<img src={pic.picture.medium} />
</div>
))}
{this.state.people.map(person => <div>{person.name.first}</div>)}
響應data.results
是一個對象數組,其中每個對象都包含name
屬性。 您需要更改渲染功能以顯示名稱
render() {
return (
<div>
{
this.state.pictures.map(item =>(
<div>
<img src={item.picture.medium} />
<div>{item.name.first}</div>
</div>))
}
</div>
);
}
您用來存儲結果的pictures
名稱不合適,請注意命名部分。
希望這會有所幫助!
考慮到API響應中沒有所謂的pictures
或people
,因此我認為您使用的變量名稱沒有意義。
您要做的是將數據置於狀態,然后在其上循環。
簡而言之,您將具有以下內容:
class App extends Component {
state = { data: [] }
componentWillMount() {
fetch('https://randomuser.me/api/?results=10')
.then(results => results.json())
.then(data => this.setState({ data: data.results }))
}
render() {
if (!this.state.data) {
return 'loading'
}
console.log(this.state.data)
return (
<div>
{
this.state.data.map(item => (
<div>
<img src={item.picture.medium} />
<p>{item.name.first}</p>
</div>
))
}
</div>
);
}
}
export default App;
有一個工作示例這里 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.