【问题标题】:using axios in service object in React Native fails在 React Native 的服务对象中使用 axios 失败
【发布时间】:2018-12-08 13:46:45
【问题描述】:

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

我设置了我的 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-native axios


    【解决方案1】:

    您期望从您的get 返回一个Promise,因为您在其上使用了thencatch,但您只是返回响应或错误。

    如果您想使用.then,您的get 函数应如下所示:

    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);
         });
     });
    };
    

    【讨论】:

    • 谢谢。这是有道理的并且确实解决了错误,但现在,屏幕中只显示加载图标。检查终端,显示“将从 api 获取数据”和“正在运行...”,但没有其他内容。 API 日志显示没有进行 API 调用
    • 好的,对 url 进行硬编码是可行的,所以它似乎是在发生其他事情。感谢您的帮助!
    猜你喜欢
    • 2021-10-25
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    • 2020-04-05
    • 2022-11-08
    • 2018-09-05
    相关资源
    最近更新 更多