问题描述
我是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不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!