javascript - this.state.xxx.map 不是函数
问题描述
我正在尝试显示来自该州的数据,但是当我尝试映射数据时,出现错误提示
this.state.xxx.map 不是函数
import React, { Component } from 'react';
import axios from 'axios';
export default class Content extends Component {
constructor(){
super();
this.state = {
gifs: [{}]
}
}
componentDidMount(){
axios.get('https://api.giphy.com/v1/gifs/random?api_key=nNwaquW24K8gLDmrxGTmawppQoTkXxLQ&tag=&rating=G')
.then( response => {
this.setState({ gifs: response.data.data})
})
.catch(function(error){
console.log(error);
})
}
render() {
return (
<div>
{this.state.gifs.map( gif =>
<p>{gif.url}</p>
)}
</div>
);
}
}
解决方案
这是工作演示:
api 将响应单个 gif 图像并且它是对象,在您的状态 gifs 是数组,因此您必须将新对象推送到 gifs 数组中,或者您可以使用扩展运算符“...”[...this.state.gifs,newGIFobject]
添加到 gif 数组中。
const {Component} = React;
class Content extends Component {
constructor(){
super();
this.state = {
gifs:[]
}
}
componentDidMount(){
axios('https://api.giphy.com/v1/gifs/random?api_key=nNwaquW24K8gLDmrxGTmawppQoTkXxLQ&tag=&rating=G')
.then( response => {
console.log(response);
this.setState({ gifs: [...this.state.gifs, response.data.data]})
})
.catch(function(error){
console.log(error);
})
}
render() {
return (
<div>
{this.state.gifs.map(gif => <p>{gif.url}</p>)}
</div>
);
}
}
// Render it
ReactDOM.render(
<Content />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<div id="react"></div>
推荐阅读
- python - Python 数组 rows*1column numpy for numpy.dot(matrix,matrix2)
- javascript - React 组件无法读取未定义的属性
- python - 在 Raspbian 上手动安装 Python 库
- azure - Sql Server 中是否有办法查找视图中的哪些列未编入索引
- intellij-idea - 不要在 PhpStorm 中封装 else ifs
- mercurial - 查找更改 TortoiseHg 中特定文件的所有提交
- php - Laravel 5.6 - 更新唯一属性
- css - asp.net core Angular Template如何添加site.css
- javascript - 为什么在 process.env 上定义属性会导致奇怪的条件分支?
- ios - 使用单个推送动画推送和呈现视图控制器