如何 return API 数据到一个单独的组件 - React Native

How to return API data to a separate component - 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;

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

我的两分钱,我总是把异步任务放在 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
          });
        });
}