经过大量搜索,我意识到 React Native 不支持 fetch api 中的流式传输,因此 fetch 调用会挂起,直到流结束。 谁能详细解释一下,RN团队无法实现的问题是什么?
我有纯 JS 代码,一切正常并且收到的数据分块。
fetch("URL")
.then((response) => response.body)
.then((rb) => {
const reader = rb.getReader();
return new ReadableStream({
start(controller) {
function push() {
reader.read().then(({ done, value }) => {
if (done) {
console.log("done", done);
controller.close();
return;
}
console.log(done, value);
push();
});
}
push();
},
});
})
.then((stream) =>
new Response(stream, { headers: { "Content-Type": "text/html" } }).text()
)
.then((result) => {
console.log('Result: ',result);
});
但是当我在我的 rn 项目中复制/粘贴此代码时,它不起作用,并且 fetch 挂起并立即收到响应。
React 原生流媒体现在可以通过 https://github.com/react-native-community/fetch。
这实际上是 RN 团队一段时间内从未解决过的一个错误,这个存储库的出现是为了提供符合 WHATWG 规范的更好的获取
这是 GitHub 的 fetch polyfill 的一个分支,React Native 目前提供了 fetch 实现。该项目采用直接构建在 React Native 网络 API 之上的替代 fetch 实现,而不是 XMLHttpRequest 来提高性能。同时,它旨在填补 WHATWG fetch 规范的一些空白,即对文本流的支持。
使用方法如下:
$ npm install react-native-fetch-api --save
fetch('https://jsonplaceholder.typicode.com/todos/1', { reactNative: { textStreaming: true } })
.then(response => response.body)
.then(stream => ...)
您可以像普通浏览器获取一样使用流对象。
希望这有帮助!