如何使用 redux 在 React 本机中使用线程调用 API?



如何在 React native 中调用后台线程.使用后台线程创建应用程序来调用 API。建议我实现这一点。

import React, { Component } from 'react'
import { WebView } from 'react-native'
export default class BackgroundTaskRunner extends Component {
render() {
return (
<WebView
ref={el => this.webView = el}
source={{html: '<html><body></body></html>'}}
onMessage={this.handleMessage}
/>
)
}
runJSInBackground (code) {
this.webView.injectJavaScript(code)
}
handleMessage = (e) => {
const message = e.nativeEvent.data
console.log('message from webview:', message)
}
}

这是调用后台线程的方法,或者有没有更好的方法来使用线程执行 API 调用?

React-native 不支持多线程。因此,要调用 api,您可以使用 redux 来调度一个操作,该操作又通过 axios 调用 API。因此,无论是通过 redux 方法,还是您可以使用简单的 axios 库。

我建议你使用axios,因为它会很整洁,你可以简单地做到这一点:

import axios from './axiosWrapper';
export const getItineryRequest = async tripId => {
const params = {
packageId: '26169',
packageId: tripId,
ip: 'true',
};
return await axios.get('app/user-package-details/', {params});
};

其中axios.get是获取请求。希望对您有所帮助。随意怀疑

有 react-native-threads,它是目前可用的最接近多线程的线程。了解为什么 Javascript 不支持多线程。

你试图实现的目标实际上是很常见的,并且通过公共库实现,Javascript 并发执行代码而不是并行执行代码,除非您正在做 CPU 密集型工作,否则不会区分。

这是一个可以在 React Native 中开箱即用的代码片段。注意fetch这里是一个全局变量。React Native 文档是一个很好的入门场所。

function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}

最新更新