我在使用 XMLHttpRequest 进行本机响应时阅读了 SOAP API 。一切都好。但是我无法读取'onreadystatechange'中的状态。当我尝试读取状态时,是通过“未定义状态错误” 进行的。在我的代码中,我想在请求运行时显示加载程序,并在请求完成时将其隐藏。我认为一种状态正在破坏“ onreadystatechange”内部。
谢谢。
代码如下:
//import libraries
import React, { Component } from "react";
import renderIf from "../../main/renderIf";
import {
View,
StyleSheet,
Text,
TextInput,
Platform,
ToastAndroid
} from "react-native";
import Constant from "../../../utils/Constant";
import Loader from "../../main/loader";
var XMLParser = require("react-xml-parser");
// create a component
class Screen extends Component {
url =
"some url";
constructor(props) {
super(props);
this.state = {
show: false,
loading: false,
error: ""
};
}
SOAPRequest(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", this.url, true);
// build SOAP request
var sr =
"<soapenv:Envelope>" +
"<soapenv:Header/>" +
"<soapenv:Body>" +
"<ns:InquiryRequest>" +
"</ns:InquiryRequest>" +
"</soapenv:Body>" +
"</soapenv:Envelope>";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
console.log("success", xmlhttp.responseText);
console.log("--------------------------------------");
console.log(this.state); // here I get Undefined state Object
}
}
};
// Send the POST request
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send(sr);
};
onSubmit = () => {
console.log(JSON.stringify(this.state));
this.state.loading = true;
this.setState({ ...this.state });
this.SOAPRequest(this);
};
render() {
return (
<KeyboardAwareScrollView
keyboardShouldPersistTaps="always"
enableAutomaticScroll={true}
enableOnAndroid={true}
>
<View style={styles.container}>
<Loader loading={this.state.loading} />
</View>
<View>
<RkButton
onPress={this.onSubmit}
>
<Text
style={{
fontWeight: "bold",
fontSize: 18,
color: "white"
}}
>
Submit
</Text>
</RkButton>
</View>
</KeyboardAwareScrollView>
);
}
}
答案 0 :(得分:4)
首先,您需要绑定函数SOAPRequest
,最简单的方法是使其成为箭头函数
SOAPRequest = () => {
然后,您可以通过将this
分配给函数中的变量来防止丢失。
SOAPRequest = () => {
const that = this; // assign this to the variable that
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", this.url, true);
// build SOAP request
var sr =
"<soapenv:Envelope>" +
"<soapenv:Header/>" +
"<soapenv:Body>" +
"<ns:InquiryRequest>" +
"</ns:InquiryRequest>" +
"</soapenv:Body>" +
"</soapenv:Envelope>";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
console.log("success", xmlhttp.responseText);
console.log("--------------------------------------");
console.log(that.state); // use that instead of this
}
}
};
// Send the POST request
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send(sr);
};