繁体   English   中英

我试图 map 数据库中的数据并收到此错误。 TypeError:无法读取未定义的属性“地图”

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM