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

£可爱£侵袭症+ 提交于 2019-12-02 15:13:23

问题


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;

here my api calling

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);
    },
    }
and I get the following error: TypeError: this.state.patients.map is not a function

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


回答1:


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

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

EDIT: Based on the comments, the patients object looks like

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

so the this.setState() call needs to be

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



回答2:


You can also do something like this as an conditional rendering. It will check that if this.state.patient exists then only it will go ahead and call this.state.patients.map function. It will also ensure that you don't receive any errors later on due to bad responses.

I updated your Patients Code example.

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;

I hope it helps. Thanks!!



来源:https://stackoverflow.com/questions/51534747/typeerror-this-state-patients-map-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!