在React Native中在服务对象中使用axios失败

时间:2018-12-08 13:46:45

标签: 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调用尚未完成,但是由于它是异步的,因此如何确保从屏幕上调用它时它已经完成?

1 个答案:

答案 0 :(得分:2)

您期望Promise会返回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);
     });
 });
};

希望这会有所帮助。快乐编码:)