【发布时间】:2017-06-15 18:21:22
【问题描述】:
我正在尝试学习 React,并且在 Javascript 方面我是初学者。现在我正在开发一个从 Flickr 的 API 获取数据的应用程序。问题是当我尝试在 Main.js 组件中的道具上使用 map 方法时,我收到一条错误消息“未捕获的 TypeError:this.props.photos.map 不是函数”。在 Stackoverflow 上搜索后,我认为问题在于 this.props 是 javascript 对象而不是数组。问题是我不知道如何使它成为一个数组。谁能解释我做错了什么?
我的代码:
class App extends Component {
constructor() {
super();
this.state = {
}
}
componentDidMount() {
let apiKey = 'xxxxxxxxxxxxxxxxxx';
let searchKeyword = 'nature';
let url = `https://api.flickr.com/services/
rest/?api_key=${apiKey}&method=flickr.photos.
search&format=json&nojsoncallback=1&&per_page=50
&page=1&text=${searchKeyword}`;
fetch(url)
.then(response => response.json())
.then(data => data.photos.photo.map((x) => {
this.setState({
farm: x.farm,
id: x.id,
secret: x.secret,
server: x.server})
// console.log(this.state)
}))
}
render() {
return (
<div className="App">
<Header />
<Main img={this.state.photos} />
<Navigation />
</div>
);
}
}
export default class Main extends Component {
render() {
return(
<main className="main">
{console.log(this.props.photos)}
</main>
)
}
}
编辑: 为什么 this.props.img 先未定义?
【问题讨论】:
-
什么是
photo?map是Array的一个方法。 -
'我收到一条错误消息:“未捕获的 TypeError:this.props.photos.map 不是函数”'
this.props.photos.map没有出现在您引用的代码中的任何位置.data.photos.photo.map有,你是这个意思吗? -
另外:您正在调用
map并且在map回调中,您正在调用setState并且没有返回任何值,因此您将每个条目映射到undefined;你也根本没有使用map的返回值(你从then中返回它,但是没有使用得到的承诺,所以它没有被使用)。你几乎肯定不想像那样反复调用setState。 -
网址真的有换行符吗?那将无法正常工作。
标签: javascript reactjs