在我的React项目中,我得到了这个错误TypeError: Cannot read property map‘of undefined“

我是React的新手。我有一个node.js应用程序接口。我正在尝试创建登录页面。我向API发出请求,我可以得到响应。我将返回的答案放入名为"user“的状态中。我想把它打印到一个带有map功能的标签上,并检查数据。但是,我收到错误消息"TypeError: Cannot read property 'map‘of undefined“。我已经用[]定义了状态,我不知道还能做什么。

enter image description here

import React, { Component } from 'react'

export default class App extends Component {

  state = { user: [] }

  componentDidMount(){
    this.getLogin();
  }
   
  getLogin = () =>{
    let data = { 
      "email": "xxxxxx@gmail.com",
      "password": "123456"
    }

    fetch("http://localhost:5000/api/auth/login",{
      method:'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(response => console.log(response))
    .then(data => this.setState({ user : data }));    
  }
   
  render() {
      return (
          <div>
              {this.state.user.map(data => (
                <h3> {data.data.access_token} </h3>
              ))}
          </div>
      )
  }
}

{

我在这里添加了API返回的答案。

  success: true, access_token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVmY…I5M30.9r9iRA0lyXTy-MjUr2QN9RrxGneqyUoVZM8eFeXoK1s", data: {…}}
    access_token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVmYzNmYmFiNjFhOWQzMGQwNDNjY2I0OSIsIm5hbWUiOiJOZW1yYW4gQWtzYWthbCIsImlhdCI6MTYwOTc5MDI5M30.9r9iRA0lyXTy-MjUr2QN9RrxGneqyUoVZM8eFeXoK1s"
    data: {name: "Red Reddington", email: "example@gmail.com"}
    success: true
    __proto__: Object

转载请注明出处:http://www.mingyanggongyi.com/article/20230526/915177.html