在使用react / redux

时间:2017-10-09 20:49:12

标签: reactjs redux bluebird

我之前曾经和这个问题作斗争并且已经修好了,出于某种原因,我在这里做这个的方式并没有解决它。我将发布我的整个动作文件以及我调用动作的位置,以便您了解我如何使用它们。

在控制台日志中,即使在成功的情况下也不会出现任何内容。

这是我想要的过程。在组件中调用操作then我希望能够以某种方式使用该响应,或者也能够catch错误。我想在组件中执行此操作。

import { APIManager } from '../../utils';

import {
  USER_CREATED,
  USER_IS_CURRENT_USER,
  USER_LOGIN,
  USER_RECEIVED,
  USER_LOGOUT,
} from './types';

const getRequest = (path, params, actionType) => (disptach) => {
  APIManager.get(path, params)
    .then((response) => {
      const payload = response.result || response.results || response.user;
      disptach({
        type: actionType,
        payload,
        params,
      });

      return payload;
    })
    .catch((err) => {
      throw err;
    });
};

const postRequest = (path, params, actionType) => (disptach) => {
  APIManager.post(path, params)
    .then((response) => {
      const payload = response.result || response.results || response.user;
      disptach({
        type: actionType,
        payload,
        params,
      });

      return payload;
    })
    .catch((err) => {
      throw err;
    });
};

export default {
  checkCurrentUser: () => dispatch =>
    dispatch(getRequest('/API/users/currentuser', null, USER_IS_CURRENT_USER)),

  register: credentials => dispatch =>
    dispatch(postRequest('/API/users/register', credentials, USER_CREATED)),

  login: credentials => dispatch =>
    dispatch(postRequest('/API/users/login', credentials, USER_LOGIN)),

  fetchUser: id => dispatch => dispatch(getRequest(`/API/users/${id}`, null, USER_RECEIVED)),

  logout: () => dispatch => dispatch(getRequest('/API/users/logout', null, USER_LOGOUT)),
};
register(credentials) {
    this.setState({
      registerModal: false,
    });

    this.props
      .register(credentials)
      .then((response) => {
        console.log(response);
        swal({
          title: 'Thank you for joining!',
          text: `${response.username}`,
          type: 'success',
        });
      })
      .catch((err) => {
        console.log(err);
        swal({
          title: 'Oops...',
          text: err,
          type: 'error',
        });
      });
  }

  login(credentials) {
    this.setState({
      loginModal: false,
    });

    this.props
      .login(credentials)
      .then((response) => {
        console.log(response);
        swal({
          title: 'Welcome Back!',
          text: `${response.username}`,
          type: 'success',
        });
      })
      .catch((err) => {
        console.log(err);
        swal({
          title: 'Oops...',
          text: err,
          type: 'error',
        });
      });
  }

0 个答案:

没有答案