【发布时间】:2020-04-08 21:10:02
【问题描述】:
我正在尝试在 React 应用程序中为 POST 请求创建一个函数(由于我在几个地方需要它),它应该在 useEffect 语句中返回一个 responseText。我用谷歌搜索的变体不是异步的 - 在从服务器获取响应之前将字符串 console.log("JSON", json) 放入控制台 JSON undefined ...
useEffect(() => {
(async function() {
try {
const response = await post_return(postData);
const json = await JSON.stringify(response);
console.log("json", json);
} catch (e) {
console.error(e);
}
})();
}, [postData]);
const API_URL_REGISTRATION = "https:.....";
export function post_return (dataPost) {
var xhr = new XMLHttpRequest();
xhr.open("POST", API_URL_REGISTRATION, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log("xhr.status", this.status);
console.log("this.responseText", this.responseText);
return xhr.status
}
};
xhr.onload = function () {
console.log("xhr.status", this.status);
console.log("this.responseText", this.responseText);
return xhr.status;
};
xhr.onerror = function () {
alert('Error' + this.status);
};
xhr.send(JSON.stringify(dataPost));
}
也试过了:
导出异步函数 post_return (dataPost) {...
和:
xhr.onreadystatechange = 异步函数 ()
我做错了什么? 谢谢,
【问题讨论】:
-
是否必须使用 xmlhttprequest,是否可以使用内置 fetch ?
-
你可以参考这里,如果可以的话请告诉我codesandbox.io/s/59356038-so-2kxd7
标签: reactjs asynchronous post xmlhttprequest