[英]I trying to map the data from the database and getting this error. TypeError: Cannot read property 'map' of undefined
I am trying to map the data from the database and getting this error.我正在尝试 map 数据库中的数据并收到此错误。 TypeError: Cannot read property 'map' of undefined
TypeError:无法读取未定义的属性“地图”
import React from "react";
export default class Allusers extends React.Component {
state = {
people: [],
};
async componentDidMount() {
const url = "http://localhost:5000/dashboard/getuser";
const response = await fetch(url);
const data = await response.json();
console.log(data);
this.setState({ people: data.results });
}
render() {
//const peopleJSX = [];
//this.state.people.forEach((person) => {
//peopleJSX.push(
//<div key={person.id}>
//<div>{person.firstname}</div>
//<div>{person.lasttname}</div>
//</div>
//);
//});
return (
<div>
{this.state.people.map((person) => (
<div key={person.id}>
<div>{person.firstname}</div>
<div>{person.lasttname}</div>
</div>
))}
</div>
);
}
}
FYI my API is working I have tested it on Postman.仅供参考,我的 API 正在工作,我已经在 Postman 上对其进行了测试。
You need to put the state inside of the constructor of the class like the example below:您需要将 state 放入 class 的构造函数中,如下例所示:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
The code is from this example: https://reactjs.org/docs/state-and-lifecycle.html .代码来自此示例: https://reactjs.org/docs/state-and-lifecycle.html 。 Right now you just have a variable named state and it's not bound to the class.
现在你只有一个名为 state 的变量,它没有绑定到 class。
There is the correction in the above code.上面的代码中有更正。 Instead of:
代替:
this.setState({ people: data.results });
Use:利用:
this.setState({ people: data.gigs });
as the gigs are the key of the object in which the data is stored.因为演出是存储数据的 object 的关键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.