因此,我用axios发出了带有react的API请求,并尝试将json存储在状态中的数组中。但是在控制状态时,它给了我2条输出:一个是空数组,另一个是返回的对象。不知道发生了什么事。我已经尽力了。
import React from 'react';
import axios from 'axios';
import { withRouter } from 'react-router-dom';
class CustomerPage extends React.Component {
constructor(props) {
super(props);
this.state = {
customerData:[]
}
}
componentDidMount() {
const { match: { params } } = this.props;
axios.get(`http://localhost:5001/api/customer/data/${params.number}`).then(
res => {
// console.log(res.data)
const customerData = res.data
this.setState({
customerData: customerData
})
}
).catch((error) => {
console.log(error);
});
}
render() {
const { customerData } = this.state;
return(
<div>
Your Info
{ customerData.map(customer => <li key={customer._id}>{customer}</li>)}
</div>
);
}
}
export default withRouter(CustomerPage);
它给了我输出:
TypeError:customerData.map不是函数
之所以发生,是因为起初渲染customerData
为空。试试这个
<div>
Your Info
{ customerData && customerData.map(customer => <li key={customer._id}>{customer}</li>)}
</div>