我是 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/