TypeError: this.state.patients.map is not a function

TypeError: this.state.patients.map is not a function

我是 React js 的新手,我正在学习创建 React 应用程序,但我遇到了映射函数的问题:

这是我的请求以及我尝试呈现数据的方式:

class Patients extends Component {
  constructor(props) {
    super(props)
    this.state = {
      patients: []
    }
  }
  componentDidMount() {
    api.getPatients()
      .then( patients => {
        console.log( patients)
        this.setState({
          patients:  patients
        })
      })
      .catch(err => console.log(err))
  }
  render() {                
    return (
      <div className=" Patientss">
        <h2>List of Patient</h2>
        {this.state.patients.map((c, i) => <li key={i}>{c.name}</li>)}
      </div>
    );
  }
}

export default Patients;

这是我的 api 电话

import axios from 'axios';

const service = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? '/api' : 'http://localhost:3000/patient',
});

const errHandler = err => {
  console.error(err);
  throw err;
};

export default {
    service: service,
    
    getPatients() {
      return service
        .get('/')
        .then(res => res.data)
        .catch(errHandler);
    },
    }
我收到以下错误: TypeError: this.state.patients.map is not a function

我也尝试过使用 slice 但它没有用,有人知道我的代码有什么问题吗?`

根据症状 (heh),您在 api.getPatients() 中获得的 patients 对象不是数组。

console.log() 看看它到底是什么。

编辑:根据评论,patients 对象看起来像

{
  count: 24,
  patient: [...],
}

所以 this.setState() 调用需要

this.setState({patients: patients.patient})

你也可以做这样的事情作为条件渲染。它将检查如果 this.state.patient 存在,那么它只会继续并调用 this.state.patients.map 函数。它还将确保您以后不会因为错误的响应而收到任何错误。

我更新了您的患者代码示例。

class Patients extends Component {
  constructor(props) {
    super(props)
    this.state = {
      patients: []
    }
  }
  componentDidMount() {
    api.getPatients()
      .then( patients => {
        console.log( patients)
        this.setState({
          patients:  patients
        })
      })
      .catch(err => console.log(err))
  }
  render() {                
    return (
      <div className=" Patientss">
        <h2>List of Patient</h2>
        { this.state.patients && this.state.patients.map((c, i) => <li key={i}>{c.name}</li>)}
      </div>
    );
  }
}

export default Patients;

希望对您有所帮助。谢谢!!