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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 08:12:20

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})

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!!

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