[英]I am trying to map mydata from the database but i am getting this error. TypeError: Cannot read property 'map' of undefined
[英]I trying to map the data from the database and getting this error. TypeError: Cannot read property 'map' of undefined
我正在嘗試 map 數據庫中的數據並收到此錯誤。 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>
);
}
}
僅供參考,我的 API 正在工作,我已經在 Postman 上對其進行了測試。
您需要將 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>
);
}
}
代碼來自此示例: https://reactjs.org/docs/state-and-lifecycle.html 。 現在你只有一個名為 state 的變量,它沒有綁定到 class。
上面的代碼中有更正。 代替:
this.setState({ people: data.results });
利用:
this.setState({ people: data.gigs });
因為演出是存儲數據的 object 的關鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.