【问题标题】:Displaying errors from an API onto the Front End将来自 API 的错误显示到前端
【发布时间】: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


【解决方案1】:
  1. 方法一,使用“errorMessage”作为字符串。 (在setState中,设置errorMessage为字符串类型)

    catch((error) => this.setState({errorMessage: error.response.data}))

  2. 方法2,使用“errorMessage”作为数组(消息列表)

catch 没有变化,但是

在渲染方法中

<div>
{ this.state.errorMessage.map(msg => <div> {msg} </div>) }
</div>

【讨论】:

    【解决方案2】:

    在类似的情况下,我曾多次遇到此错误。在.catch() 块中尝试console.log(error.response.data) 只是为了看看你得到了什么。应该有 error.response.data.message 属性或类似的东西来存储错误的实际字符串。现在您设置的对象不是字符串。

    【讨论】:

      猜你喜欢
      • 2017-12-22
      • 2019-04-18
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多