【发布时间】: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