我正在学习有关使用 fetch 的教程;我能够使用这个模拟 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>)}
关于javascript - React 错误 - 无法读取未定义的属性 'state',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50066741/