Javascript TypeError:this.state.student.map不是函数
因此,我试图从API加载数据,但在加载过程中遇到了许多问题。我几乎什么都读了,但没用。如果有更好的方法来构造我的代码,请留下评论。欢迎一切帮助Javascript TypeError:this.state.student.map不是函数,javascript,reactjs,api,Javascript,Reactjs,Api,因此,我试图从API加载数据,但在加载过程中遇到了许多问题。我几乎什么都读了,但没用。如果有更好的方法来构造我的代码,请留下评论。欢迎一切帮助 import React, { componentDidMount, Component } from 'react'; class Students extends Component { constructor(props) { super(props); this.state = {
import React, { componentDidMount, Component } from 'react';
class Students extends Component {
constructor(props) {
super(props);
this.state = {
student: []
}
}
componentDidMount() {
fetch(`https://www.hatchways.io/api/assessment/students`)
.then(res => res.json())
.then(data => this.setState({ student: data }));
}
render() {
const students = this.state.student.map(pupil => (
<div key={pupil.id}>
<p>{pupil.firstName + ` ` + pupil.lastName}</p>
</div>
))
return (
<>
<section className="hero is-fullheight">
<div className="hero-body">
<div className="container">
{students}
</div>
</div>
</section>
</>
)
}
}
export default Students;
import React,{componentDidMount,Component}来自'React';
班级学生扩展组件{
建造师(道具){
超级(道具);
此.state={
学生:[]
}
}
componentDidMount(){
取回(`https://www.hatchways.io/api/assessment/students`)
.then(res=>res.json())
.then(data=>this.setState({student:data}));
}
render(){
const students=this.state.student.map(瞳孔=>(
{product.firstName+`+product.lastName}
))
返回(
{学生}
)
}
}
输出默认学生;
我想映射数组并从api加载所有用户。您得到的数据是一个对象,而不是数组。您可以从该对象设置学生
componentDidMount() {
fetch(`https://www.hatchways.io/api/assessment/students`)
.then(res => res.json())
.then(data => this.setState({ student: data.students }));
}
避免使用类组件,它会为react处理创建太多开销。 使用功能组件和挂钩 componentDidMount将更改为
Useeffect(()=>{
fetch(`https://www.hatchways.io/api/assessment/students`)
.then(res => res.json())
.then(data => this.setState({ student: data.students }));
},[])
如果您使用的是类组件,请尝试更改名称
不安全的组件willmount()