React native,redux和axios:UnhandledPromiseRejectionWarning

时间:2017-04-01 14:55:03

标签: node.js react-native redux axios

我有一个应用程序,您可以在其中创建许多事件,并且我已经使用express和node JS创建了一个API。在react-native projet中,我使用Axios来获取API。但我的终端有这个奇怪的错误:

(node:59293) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): RangeError: Invalid status code: 0
(node:59293) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

当我尝试创建一个事件时,在我的浏览器控制台中我有这个:

Error: Network Error
    at createError (createError.js:15)
    at XMLHttpRequest.handleError (xhr.js:87)
    at XMLHttpRequest.dispatchEvent (event-target.js:172)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:542)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:378)
    at XMLHttpRequest.js:482
    at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
    at MessageQueue.__callFunction (MessageQueue.js:242)
    at MessageQueue.js:108
    at guard (MessageQueue.js:46)

我在这里粘贴我的代码,也许我在某处错了,

BACK END PART

import Event from './model';

export const createEvent = async (req, res) => {
  const { title, description } = req.body;
  const newEvent = new Event({ title, description });

  try {
    return res.status(201).json({ event: await newEvent.save() });
  } catch(e) {
    return res.status(e.status).json({ error: true, message: 'Error with event' });
  }
};

export const getAllEvents = async (req, res) => {
  try {
    return res.status(200).json({ events: await Event.find({} )});
  } catch(e) {
    return res.status(e.status).json({ error: true, message: 'Error with all events' });
  }
};

前端部分

api.js

import axios from 'axios';

axios.defaults.baseURL = 'http://localhost:3000/api';

class EventApi {
  constructor() {
    this.path = '/events';
  }

  async fetchEvents() {
    try {
      const { data } = await axios.get(this.path);
      return data.events;
    } catch (e) {
      console.log(e);
    }
  }

  async createEventPost(args) {
    // console.log('nous entrons dans le cadre de la création dun evenement');
    try {
      console.log('nous tryons');
      const res = await axios.post(`${this.path}/new`, { ...args });
      console.log(res);
      console.log('hello world', args);
      return res;
    } catch (e) {
      console.log(e);
      console.log('lol');
    }
  }

}

export {
  EventApi
};

CreateScreen.js

import React, { Component } from 'react';
import { View } from 'react-native';
import { connect } from 'react-redux';
import DateTimePicker from 'react-native-modal-datetime-picker';
import moment from 'moment';
import { Ionicons } from '@expo/vector-icons';

import { createEvent } from './actions';
import { LoadingScreen } from '../../common';
import Colors from '../../../constants/colors';
import styles from './styles/CreateScreen';
import CreateEventsForm from './components/CreateEventsForm';

@connect(
  state => ({
    event: state.createEvent
  }),
  { createEvent }
)
export default class CreateScreen extends Component {
  static navigationOptions = {
    title: 'Créer un événement',
    header: {
      style: {
        backgroundColor: Colors.whiteColor
      },
      titleStyle: {
        color: Colors.redParty
      }
    },
    tabBar: {
      icon: ({ tintColor }) => (
          <Ionicons name="ios-create" size={25} color={tintColor} />
      )
    }
  }

  state = {
    isDateTimePickerVisible: false,
    date: moment()
  }

  _showDateTimePicker = () => this.setState({ isDateTimePickerVisible: true })

  _handleDateTimePicker = () => this.setState({ isDateTimePickerVisible: false })

  _handleDatePicked = date => {
    this.setState({ date });
    this._handleDateTimePicker();
  }

  _checkTitle() {
    const { date } = this.state;
    if (date > moment()) {
      return moment(date).format('MMMM Do YYYY, h:mm.ss a');
    }
    return 'Choisir une date';
  }

  _checkNotEmpty() {
    const { date } = this.state;
    if (date > moment()) {
      return false;
    }
    return true;
  }

  _createEvent = async values => {
    await this.props.createEvent(values);
    this.props.navigation.goBack();
  }

  render() {
    const { event } = this.props;
    if (event.isLoading) {
      return (
        <View style={styles.root}>
          <LoadingScreen />
        </View>
      );
    } else if (event.error.on) {
      return (
        <View>
          <Text>
            {event.error.message}
          </Text>
        </View>
      );
    }
    return (
      <View style={styles.root}>
        <CreateEventsForm
          createEvent={this._createEvent}
          showDateTimePicker={this._showDateTimePicker}
          checkTitle={this._checkTitle()}
        />
        <DateTimePicker
          isVisible={this.state.isDateTimePickerVisible}
          onConfirm={this._handleDatePicked}
          onCancel={this._handleDateTimePicker}
          mode="datetime"
        />
      </View>
    );
  }
}

acion.js

import { EventApi } from '../../../constants/api';
import { fetchMyEvents } from '../home/actions';

const eventApi = new EventApi();

export const CREATE_EVENT = 'CREATE_EVENT';
export const CREATE_EVENT_SUCCESS = 'CREATE_EVENT_SUCCESS';
export const CREATE_EVENT_ERROR = 'CREATE_EVENT_ERROR';

export const createEvent = args => async dispatch => {
  dispatch({ type: CREATE_EVENT });
  try {
    await eventApi.createEventPost(args);
    dispatch({ type: CREATE_EVENT_SUCCESS });
  } catch (e) {
    return dispatch({ type: CREATE_EVENT_ERROR });
  }
  return await dispatch(fetchMyEvents());
};

reducer.js

import { CREATE_EVENT, CREATE_EVENT_ERROR, CREATE_EVENT_SUCCESS } from './actions';

const INITIAL_STATE = {
  error: {
    on: false,
    message: null
  },
  isLoading: false
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case CREATE_EVENT:
      return {
        ...INITIAL_STATE,
        isLoading: true
      };
    case CREATE_EVENT_SUCCESS:
      return {
        ...INITIAL_STATE,
        isLoading: false
      };
    case CREATE_EVENT_ERROR:
      return {
        error: {
          on: true,
          message: 'Error happened'
        },
        isLoading: false
      };
    default:
      return state;
  }
};
不要问你是否需要更多代码(例如CreateEventsForm)

谢谢!

1 个答案:

答案 0 :(得分:1)

看起来原始错误正在被吞噬。我发现类似问题的一个解决方案似乎是放弃react-native - https://github.com/mzabriskie/axios/issues/640的版本,但更好的方法是发现原始错误然后你应该能够解决这个问题 - {{ 3}}: