react-native - 在 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 调用尚未完成,但由于它是异步的,我如何确保从屏幕调用它时它已经完成?
解决方案
您期望 aPromise
从您返回,get
因为您正在使用它then
,catch
但您只是返回响应或错误。
如果你想使用它,你的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);
});
});
};
推荐阅读
- java - 无法使用 EditText Android 添加像 0.25 这样的小数
- plsql - 通过触发器-PLSQL 获取新插入的记录时出错
- clojure - 在 ClojureScript 中序列化 JavaScript 对象
- javascript - Rails 6 加载所需的自定义 JS,但这些功能都不起作用
- css - 我们可以在 react native 中使用 rems 来设置组件的样式吗
- google-assistant-sdk - 如何使用 Google Assistant 中的“Fulfillment URL”在响应中获取 language_code
- android - 在准确的时间使用 Job Scheduler 执行后台任务
- javascript - 通过 iframe 获取和打印 PDF 文件会产生白页
- php - 使用 cron-job 更新 WordPress 发布帖子的日期
- javascript - 静态快递不提供简单的html页面