值不是替换,函数返回0.如何修复? (react-native 0.30,IOS 10.0模拟器)
export function getCategoryList() {
var xhr = new XMLHttpRequest();
jsonResponse = null;
xhr.onreadystatechange = (e) => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
console.log('SUCCESS', xhr.responseText);
jsonResponse = JSON.parse(xhr.responseText);
} else {
console.warn('request_error');
}
};
xhr.open('GET', 'https://httpbin.org/user-agent');
xhr.send();
return jsonResponse;
}
答案 0 :(得分:2)
您不能像这样返回值。
我建议使用回调或承诺:
回调:
function getCategoryList(callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = (e) => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
console.log('SUCCESS', xhr.responseText);
callback(JSON.parse(xhr.responseText));
} else {
console.warn('request_error');
}
};
xhr.open('GET', 'https://httpbin.org/user-agent');
xhr.send();
}
getCategoryList(data => console.log("The data is:", data));
承诺:
function getCategoryList() {
var xhr = new XMLHttpRequest();
return new Promise((resolve, reject) => {
xhr.onreadystatechange = (e) => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
console.log('SUCCESS', xhr.responseText);
resolve(JSON.parse(xhr.responseText));
} else {
console.warn('request_error');
}
};
xhr.open('GET', 'https://httpbin.org/user-agent');
xhr.send();
});
}
getCategoryList().then(res => console.log("The result is", res));
答案 1 :(得分:0)
如果XHR是同步的(xhr.open('GET', 'https://httpbin.org/user-agent', false)
),您可以返回请求响应,执行一个在请求完成时中断的无限循环。
注意:
function getCategoryList() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://httpbin.org/user-agent", false);
xhr.send();
// stop the engine while xhr isn't done
for(; xhr.readyState !== 4;)
if (xhr.status === 200) {
console.log('SUCCESS', xhr.responseText);
} else console.warn('request_error');
return JSON.parse(xhr.responseText);
}