类型错误:this.state.patients.map 不是函数 [英] TypeError: this.state.patients.map is not a function
问题描述
我是 React js 的新手,我正在学习创建一个 React 应用程序,但我遇到了映射函数的问题:
这是我的请求以及我尝试呈现数据的方式:
class 患者扩展组件 {构造函数(道具){超级(道具)this.state = {耐心: []}}componentDidMount() {api.getPatients().then( 患者 => {控制台日志(患者)this.setState({患者:患者})}).catch(err => console.log(err))}使成为() {返回 (<div className="患者"><h2>患者名单</h2>{this.state.patients.map((c, i) => <li key={i}>{c.name}</li>)}
);}}导出默认患者;
这里是我的 api 调用
从 'axios' 导入 axios;const 服务 = axios.create({baseURL: process.env.NODE_ENV === '生产' ?'/api' : 'http://localhost:3000/patient',});const errHandler = err =>{控制台错误(错误);抛出错误;};导出默认{服务:服务,获取患者(){退货服务.得到('/').then(res => res.data).catch(errHandler);},}
我收到以下错误:TypeError: this.state.patients.map 不是函数
我也尝试使用切片,但没有用,有人知道我的代码有什么问题吗?`
根据症状 (heh),您在 api.getPatients()
中获得的 patients
对象不是数组.
console.log()
看看它到底是什么.
根据评论,patients
对象看起来像
<代码>{计数:24,病人: [...],}
所以 this.setState()
调用需要
this.setState({病人:病人.病人})
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?`
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})
这篇关于类型错误:this.state.patients.map 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!