【发布时间】:2021-06-05 15:31:30
【问题描述】:
我在前端使用 React,我从 API 获取数据。 当后端发生错误时,我希望能够在前端将其显示给用户。
我有一个用户提交的表单,有一个 phoneNumber 字段,只接受数字。当输入除数字以外的任何其他内容时,它会吐出一个错误。
这是我的代码:
constructor(props){
super(props);
this.state = {
shipment: {
email,
phoneNumber: "",
},
errorMessage : ""
};
submitRequest = (event) =>{
axios.post("http://localhost:8000/app/shipments/create/", this.state.shipment)
.then((response) =>{
let result = response.data;
console.log(result);
}).catch((error) =>{
this.setState({errorMessage: [error.response.data]});
});
}
这是我收到的错误的屏幕截图:
错误:对象作为 React 子对象无效(找到:对象带有键 {email, phoneNumber})。如果您打算渲染一组子项,请改用数组。
正如错误提示,我在代码中使用了一个数组:
.catch((error) =>{
this.setState({errorMessage: [error.response.data]});
【问题讨论】:
-
您似乎正在尝试渲染一个对象(也许错误是一个对象?)
标签: javascript json reactjs django-rest-framework jsx