Redux 入门教程—15redux-thunk 实践发送 ajax 请求2

一般异步请求有三种情况

Redux 入门教程—15redux-thunk 实践发送 ajax 请求2_第1张图片

 

https://randomuser.me/

https://cn.redux.js.org/docs/advanced/AsyncActions.html

components/User.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { get_user } from '../actions';

class User extends Component {
  render() {
    const { get_user } = this.props;

    const { error, isFetching, user } = this.props.user;

    let data;

    if (error) {
      data = error;
    } else if (isFetching) {
      data = "Loading...";
    } else {
      data = user.email;
    }

    return (
      

{ data }

); } } const mapStateToProps = (state) => { return { user: state.user }; }; export default connect(mapStateToProps, { get_user })(User);

actions/index.js

import axios from 'axios';
import { INCREMENT, DECREMENT } from '../constants';
import { FETCH_USER_SUCCESS, FETCH_USER_REQUEST, FETCH_USER_FAILURE } from '../constants';

export const increment = () => {
  return dispatch => {
    setTimeout(() => {
      dispatch({
        type: INCREMENT
      });
    }, 2000);
  };
};

export const decrement = () => {
  return {
    type: DECREMENT
  }
};

export const get_user = () => {
  return dispatch => {
    dispatch(fetch_user_request())
    axios.get("https://randomuser.me/api/")
      .then(res => {
        dispatch(fetch_user(res.data.results[0]));
      })
      .catch(error => {
        dispatch(fetch_user_failure(error.response.data));
      })
  };
};

export const fetch_user_failure = (error) => {
  return {
    type: FETCH_USER_FAILURE,
    error
  };
};

export const fetch_user = (user) => {
  return {
    type: FETCH_USER_SUCCESS,
    user
  }
};

export const fetch_user_request = () => {
  return {
    type: FETCH_USER_REQUEST
  }
};

reducers/user.js

import { FETCH_USER_SUCCESS, FETCH_USER_REQUEST, FETCH_USER_FAILURE } from '../constants';

const initialState = {
  isFetching: false,
  error: null,
  user: {}
};

const user = (state = initialState, action = {}) => {
  switch(action.type) {
    case FETCH_USER_SUCCESS:
      return {
        isFetching: false,
        error: null,
        user: action.user
      };
    case FETCH_USER_REQUEST:
      return {
        isFetching: true,
        error: null,
        user: {}
      }
    case FETCH_USER_FAILURE:
      return {
        isFetching: false,
        error: action.error,
        user: {}
      };
    default: return state;
  }
}

export default user;

constants/index.js

export const INCREMENT = "INCREMENT";
export const DECREMENT = "DECREMENT";

// user
export const FETCH_USER_SUCCESS = "FETCH_USER_SUCCESS";
export const FETCH_USER_REQUEST = "FETCH_USER_REQUEST";
export const FETCH_USER_FAILURE = "FETCH_USER_FAILURE";

 

你可能感兴趣的:(Redux,入门教程)