我是React JS的新手,正在学习创建React应用程序,并且映射功能出现问题:
这是我的请求以及我如何尝试呈现数据:
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
TypeError: this.state.patients.map is not a function
我也尝试使用slice但它没有用,有人知道我的代码有什么问题吗?
根据症状(嘿),patients您输入的对象api.getPatients()不是数组。
patients
api.getPatients()
console.log() 看看它到底是什么。
console.log()
编辑:根据评论,patients对象看起来像
{ count: 24, patient: [...], }
因此this.setState()通话需要
this.setState()
this.setState({patients: patients.patient})