首页 > 解决方案 > 在 React Native 的服务对象中使用 axios 失败

问题描述

我不知道为什么这不起作用。我认为这与将一个承诺嵌套在另一个承诺中有关:

我设置了我的 api 服务对象:

api.js

import axios from 'axios';
import apiConfig from './apiConfig';
import deviceStorage from '../services/deviceStorage.js';

export const get = (endpoint, payload = {}, headers = {}) => {
  const jwt = deviceStorage.loadJWT

  headers.Authorization = jwt
  console.log("running..");

  axios({
    method: 'GET',
    url: apiConfig.development.url + endpoint,
    headers: headers,
    data: payload,
  }).then((response) => {
    console.log('will return response..');
    return response;
  }).catch((error) => {
    console.log('will return error..');
    return error;
  });
};

然后我从屏幕上调用它:

NotificationsScreen.js

import React from 'react';
import { View, ScrollView, Text, Button, StyleSheet } from 'react-native';
import axios from 'axios';
import Header from '../components/Header';
import NotificationCardSection from '../components/notificationsScreen/NotificationCardSection';
import NotificationCardList from '../components/notificationsScreen/NotificationCardList';
import { Loading } from '../components/common/';
import globalStyles from '../globalStyles';
import * as api from '../services/api'

export default class NotificationsScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      notifications: [],
      error: ''
    };
  }

  componentDidMount() {
    console.log("will get data from api");
    api.get(
      '/notifications'
    ).then((response) => {
      console.log("got back data from api");
      this.setState({
        notifications: response.data.data,
        loading: false
      });
    }).catch((error) => {
      console.log("got error from api");
      this.setState({
        error: 'Error retrieving data',
        loading: false
      });
    });
  }

但我得到一个错误:

TypeError: Cannot read property 'then' of undefined.

终端显示'running..'但不显示'will return response...''will return error'因此它们没有触发。

我认为这是因为 api 调用尚未完成,但由于它是异步的,我如何确保从屏幕调用它时它已经完成?

标签: react-nativeaxios

解决方案


您期望 aPromise从您返回,get因为您正在使用它thencatch但您只是返回响应或错误。

如果你想使用它,你的get函数应该如下所示.then

export const get = (endpoint, payload = {}, headers = {}) => {
  return new Promise((resolve, reject) => {
     const jwt = deviceStorage.loadJWT

      headers.Authorization = jwt
      console.log("running..");

      axios({
        method: 'GET',
        url: apiConfig.development.url + endpoint,
        headers: headers,
        data: payload,
      })
      .then((response) => {
        console.log('will return response..');
        resolve(response);
      })
      .catch((error) => {
        console.log('will return error..');
        reject(error);
     });
 });
};

推荐阅读