TypeError:this.state.patients.map不是函数 [英] TypeError: this.state.patients.map is not a function

查看:130
本文介绍了TypeError:this.state.patients.map不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是React JS的新手,我正在学习创建React应用程序,并且映射功能出现问题:

i am new in react js,and i am learning to create a React application and I got a problem with mapping function:

这是我的请求以及我如何呈现数据的方式:

Here's my request and how I am attempting to render the data:

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

and I get the following error: TypeError: this.state.patients.map is not a function

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

i've try to use slice aswell but it didnt work, anyone know whats wrong with my code?`

推荐答案

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

Based on the symptoms (heh), the patients object you get in api.getPatients() isn't an array.

console.log()它可以查看它的实际含义.

console.log() it to see what it actually is.

根据注释,patients对象看起来像

Based on the comments, the patients object looks like

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

因此this.setState()通话需要

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

这篇关于TypeError:this.state.patients.map不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆