Javascript TypeError:使用axios.get时,this.state.persons.map不是函数
我是React的初学者,尝试从中获取数据。我使用stateperson存储json数据,并将其显示在div->data包装器中 现在,我只想从json文件中提取名称,并确保state persons是一个空数组而不是字符串 请帮忙 反应JS文件Javascript TypeError:使用axios.get时,this.state.persons.map不是函数,javascript,json,reactjs,axios,Javascript,Json,Reactjs,Axios,我是React的初学者,尝试从中获取数据。我使用stateperson存储json数据,并将其显示在div->data包装器中 现在,我只想从json文件中提取名称,并确保state persons是一个空数组而不是字符串 请帮忙 反应JS文件 import React, { Component } from 'react' import './form.css' import axios from 'axios' class form extends Component{ cons
import React, { Component } from 'react'
import './form.css'
import axios from 'axios'
class form extends Component{
constructor(props){
super(props);
this.state={
answer:'',
persons:[]
}
this.handleChange=this.handleChange.bind(this);
this.handleSubmit=this.handleSubmit.bind(this);
}
componentDidMount(){
axios.get('https://api.randomuser.me')
.then(res=>{
console.log(res);
this.setState({persons:res.data});
})
}
handleSubmit=(e)=>{
}
handleChange=(e)=>{
this.setState({
answer:e.target.value,
})
}
render(){
return (
<div>
<section className="login">
<div className="loginContainer">
<div className="heading">
</div>
<div className="data-wrapper">
{this.state.persons.map(person=><h2>{person.name}</h2>)}
</div>
</div>
</section>
</div>
)
}
}
export default form
您需要从正确的
键
访问数据。您需要设置:
this.setState({ persons: res.data.results });
此外,您需要将名称呈现为字符串,当前,您正在呈现将引发错误的对象
<h2>{person.name.first}</h2>
{person.name.first}
this.setState({ persons: res.data.results });
<h2>{person.name.first}</h2>