javascript - $.post 错误回调中的 ReactDOM.render

标签 javascript post reactjs react-dom

我是 React 新手,并尝试在 POST 请求返回错误时呈现错误消息。像这样的事情:

$.post({
    url: `/abc/xyz/`,
    cache: false,
    dataType: 'json',
    data: data,
    contentType: 'application/json; charset=utf-8',
    success: function (response) {
        ...
    },
    error: function (response) {    
        ReactDOM.render(
            <div>
                <p>response.statusText</p>
            </div>,
            document.getElementById('errorDialog')
        );
    }
});

但是,当我尝试运行它时,在控制台中我不断收到错误:

Uncaught Error: Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.

仔细检查发现问题出在错误回调内的 ReactDOM.render 行中。这不能在回调中使用吗?我尝试在外部使用它,但可能由于回调函数的异步性质,它不起作用。有人知道我该如何解决这个问题吗?提前致谢!

最佳答案

首先,您似乎收到了发生了最小化异常错误,因为ReactDOM没有找到id为errorDialog的元素,接下来您根据您的设置使用 $.post 而不是 $.ajax...我建议您为 statusText 设置一种状态并保存您获得的值。我给你准备了一个例子。 ES6:

import React, { Component } from 'react';

export default class App extends Component {

  constructor() {
    super();
    this.state = {
      statusText: null
    };
  }

  componentDidMount() {
    $.ajax({
        type: 'POST'
        url: `/abc/xyz/`,
        cache: false,
        dataType: 'json',
        data: data,
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
          console.log("$.post success", response);
        },
        error: function (response) {
          this.setState({
            statusText: response.statusText
          });
        }
    }.bind(this));
  }

  render() {
    const { statusText } = this.state;
    return (
      <div>
        <p>{statusText}</p>
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('errorDialog'));

关于javascript - $.post 错误回调中的 ReactDOM.render,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39337662/

相关文章:

javascript - 将数组转换为修改后的对象

javascript - 将 EventListener 添加到表单,在表单中实际调用提交的任何子 &lt;input&gt; 上运行提交函数

security - 在 POST 请求上使用 XSS 窃取信息的场景是什么

http - Web 服务器如何知道发布给它们的表单中使用的字符集?

reactjs - useState Hook 给出 "not a function"错误

javascript - 添加到变量达到条件边界,但条件行为不会发生

javascript - 在 Firebase 中通过键查找对象

json - 使用 alamofire 将带有 JSON 对象和查询参数的 POST 请求发送到 REST web 服务

javascript - 当axios发出post请求时会发生什么?

javascript - 无法读取ReactJS中未定义的属性 'enqueueSetState'