如何使用React Native Rxjs?

huangapple go评论61阅读模式
英文:

How to use React Native Rxjs?

问题

export async function getAllStock() {
try {
let data;
await Axios.get("stocks/find-all", config)
.pipe(retry(2))
.subscribe(
async (response) => {
return await response.data;
},
(error) => console.log(error)
);
} catch (err) {
console.log(err);
}
}

我正在使用这个库在我的React Native项目中从API获取记录

useEffect(() => {
const getData = async () => {
console.log(await getAllStock());
};
getData();
}, []);

实际上,我的目标是订阅响应数据,响应数据应该被订阅,并且更改应该立即反映在屏幕上。但始终返回未定义的响应数据。

英文:
export async function getAllStock() {
    try {
        let data;
        await Axios.get("stocks/find-all", config)
            .pipe(retry(2))
            .subscribe(
                async (response) => {
                    return await response.data;
                },
                (error) => console.log(error)
            );
    } catch (err) {
        console.log(err);
    }
}

https://github.com/zhaosiyang/axios-observable
I am using this library to get records from API in my React Native project

  useEffect(() => {
        const getData = async () => {
            console.log(await getAllStock());
        };
        getData();
    }, []);

Actually my goal is to subscribe to response data,response data should be subscribed and changes should be reflected on the screens instantly. But always undefined response data

答案1

得分: 2

以下是已翻译的内容:

似乎您正在尝试在React Native项目中使用Axios与可观察对象来获取数据。但是,您提供的代码存在一些问题。以下是如何修改代码以正确处理可观察对象并获取响应数据的方法:

  1. 安装必要的依赖项:首先,请确保已安装所需的依赖项。您提到正在使用axios-observable库,因此您需要安装它:
npm install axios axios-observable rxjs
  1. 修改您的getAllStock函数:
import { Observable } from 'rxjs';
import { AxiosObservable } from 'axios-observable';
import Axios from 'axios';

export function getAllStock() {
  const axiosObservable = AxiosObservable.create({
    method: 'GET',
    url: 'stocks/find-all',
    headers: { ...config.headers }, // 假设config在某处定义。
  }).pipe(retry(2));

  return axiosObservable;
}

在此代码中,我们创建了一个AxiosObservable并将retry操作符传递给它。该函数现在返回可观察对象。

  1. 修改您的useEffect
import { useEffect } from 'react';
import { getAllStock } from './your-module'; // 导入您的getAllStock函数

function YourComponent() {
  useEffect(() => {
    const subscription = getAllStock().subscribe(
      (response) => {
        console.log(response.data); // 在此处处理响应数据
      },
      (error) => {
        console.log(error);
      }
    );

    // 不要忘记在组件卸载时取消订阅。
    return () => {
      subscription.unsubscribe();
    };
  }, []);

  // 其余的组件代码
}

现在,当您调用getAllStock()时,它将返回一个可观察对象,您可以订阅它。当接收到响应数据时,它将被记录,您可以根据需要处理它。请确保调整导入路径,并根据需要将代码整合到您的项目结构中。

英文:

It seems like you are trying to use Axios with observables to fetch data in your React Native project. However, the code you provided has some issues. Here's how you can modify your code to properly handle the observable and get the response data: 1. Install the necessary dependencies: First, make sure you have the required dependencies installed. You mentioned that you are using the axios-observable library, so you'll need to install it:

npm install axios axios-observable rxjs
  1. Modify your getAllStock function:
import { Observable } from 'rxjs';
import { AxiosObservable } from 'axios-observable';
import Axios from 'axios';

export function getAllStock() {
  const axiosObservable = AxiosObservable.create({
    method: 'GET',
    url: 'stocks/find-all',
    headers: { ...config.headers }, // Assuming config is defined somewhere.
  }).pipe(retry(2));

  return axiosObservable;
}

In this code, we create an AxiosObservable and pipe the retry operator to it. The function now returns the observable.

  1. Modify your useEffect:

import { useEffect } from 'react';
import { getAllStock } from './your-module'; // Import your getAllStock function

function YourComponent() {
  useEffect(() => {
    const subscription = getAllStock().subscribe(
      (response) => {
        console.log(response.data); // Handle the response data here
      },
      (error) => {
        console.log(error);
      }
    );

    // Don't forget to unsubscribe when the component unmounts.
    return () => {
      subscription.unsubscribe();
    };
  }, []);

  // Rest of your component code
}

Now, when you call getAllStock(), it will return an observable that you can subscribe to. When the response data is received, it will be logged, and you can handle it as needed. Make sure to adjust the import paths and incorporate the code into your project structure as necessary.

huangapple
  • 本文由 发表于 2023年4月17日 18:18:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034081.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定