首页 > 解决方案 > 如何将 API 数据返回到单独的组件 - React Native

问题描述

我正在从本机应用程序中的 API 获取数据并将其显示为列表。

下面是我的代码:

async componentWillMount() {
    if (Platform.OS === 'android') {
        BackHandler.addEventListener('hardwareBackPress', this.backPressed);
    }
    this.fetchNotifications();
}
}

async fetchNotifications() {
    this.setState({refreshing: true});

    const config = getAppConfig();
    const cognitoToken = await this.getCognitoToken(config);
    if (cognitoToken !== null) {
        let headers = await this.getRequestHeaders(cognitoToken);
        let body = this.getRequestBody(config);
        let notificationUrl = config["notification-retrieve-api"];

        return fetch(notificationUrl,
            {
                method: 'POST',
                headers: headers,
                body: body
            }).then((response) => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error('Something went wrong');
            }
        })
        .then((notifications) => {
            console.log(JSON.stringify(notifications));
            this.setState({
                notifications,
                error: null,
                refreshing: false
            });
        }).catch((error) => {
            this.setState({
                notifications: [],
                error,
                refreshing: false
            });
        });
    }
}

这工作正常。我可以从 API 中检索数据。

现在我想将 API 代码与我的屏幕组件分开。我将在我的屏幕组件中调用“fetchNotifications”作为一个函数。我正在尝试这样做,但它根本不起作用。

这就是我正在做的事情:

async componentWillMount() {
    if (Platform.OS === 'android') {
        BackHandler.addEventListener('hardwareBackPress', this.backPressed);
    }
    let response = fetchNotifications();

    this.setState({
        notifications: response,
        error: null,
        refreshing: false
    })
}
}

async function fetchNotifications() { //now this function is in another component
.
.
.
.

    if(cognitoToken !== null) {
        let headers = await this.getRequestHeaders(cognitoToken);
        let body = this.getRequestBody(config);
        let notificationUrl = config["notification-retrieve-api"];

        return fetch(notificationUrl,
            {
                method: 'POST',
                headers: headers,
                body: body
            }).then((response) => {
            if (response.ok) {
                response.json();
            } else {
                throw new Error('Something went wrong');
            }
        })
        .then((response) => {
            return response;
        }).catch((error) => {
            this.setState({
                notifications: [],
                error,
                refreshing: false
            });
        });
    }
}

export default fetchNotifications;

这种方式正确吗?谁有更好的解决方案?

标签: reactjsreact-nativefetch-api

解决方案


我的两分钱,我总是把异步任务放在里面Promise,包括 API 请求。

// API helper file
export const fetchNotifications = (params) => {
return new Promise(async (resolve, reject)=>{
    try{
       const headers = getHeaders(params)
       const body = getBody(params)
       const response = await fetch(notificationUrl,
        {
          method: 'POST',
          headers: headers,
          body: body
        })
          if (response.ok) {
            const responseObj = await response.json();
            resolve(responseObj)
          } else {
            throw new Error('Something went wrong');
          }
    } catch (e) {
        // something went wrong
        generalHandler(e) // logging etc. 
        reject(e) // for ui handling
    }
}
}

然后我们可以在任何地方使用它

import { fetchNotifications } from '.../APIHelper'

在您的 ui 文件中:

componentWillMount() {
   fetchNotifications(params)
       .then((notifications) => {
          console.log(JSON.stringify(notifications));
          this.setState({
            notifications,
            error: null,
            refreshing: false
          });
        }).catch((error) => {
          this.setState({
            notifications: [],
            error,
            refreshing: false
          });
        });
}

推荐阅读