在React Native中通常是通过 Ajax 请求从服务器获取数据,然后在componentDidMount 方法中创建 Ajax 请求,等到请求成功,然后再用 this.setState 方法重新渲染 UI。
一、fetch
fetch 目前还不是 W3C 规范,由 whatag 负责出品。与 Ajax 不同的是,它的 API 不是事件机制,而采用了目前流行的 Promise 方式处理。
来看写法例子
fetch('http://blog.duicode.com/?json=1', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
也可以使用传统的form表单形式提交
fetch('http://blog.duicode.com/?json=1', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'key1=value1&key2=value2'
})
另外注意在处理服务器响应的时候是异步异步异步,异步的意思是你应该趁这个时间去做点别的事情,比如显示loading,而不是让界面卡住傻等!
getDataFromApi(url) {
return fetch(url)
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
二、其他AJAX网络库
React Native中已经内置了XMLHttpRequest API(也就是俗称的ajax)。一些基于XMLHttpRequest封装的第三方库也可以使用,例如frisbee或是axios等。但注意不能使用jQuery,因为jQuery中还使用了很多浏览器中才有而RN中没有的东西(所以也不是所有web中的ajax库都可以直接使用)。
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
} else {
console.warn('error');
}
};
request.open('GET', 'http://blog.duicode.com/?json=1');
request.send();
三、 WebSocket
React Native还支持WebSocket
var ws = new WebSocket('ws://host.com/path');
ws.onopen = () => {
// 打开一个连接
ws.send('something'); // 发送一个消息
};
ws.onmessage = (e) => {
// 接收到了一个消息
console.log(e.data);
};
ws.onerror = (e) => {
// 发生了一个错误
console.log(e.message);
};
ws.onclose = (e) => {
// 连接被关闭了
console.log(e.code, e.reason);
};