剧场模式
首页前端ReactRedux 入门教程(React 进阶)

Redux 入门教程 #15 redux-thunk 实践发送 ajax 请求 part 1

海外散仙厉飞雨 · 真仙发布于
5

https://randomuser.me/

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, user } = this.props;
    return (
      <div>
        <h1 className="jumbotron-heading text-center">{ user.email }</h1>
        <p className="text-center">
          <button onClick={ () => get_user() } className="btn btn-success mr-2">GET RANDOM USER</button>
        </p>
      </div>
    );
  }
}

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 } from '../constants';

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

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

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

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

reducers/user.js

import { FETCH_USER_SUCCESS } from '../constants';

const user = (state = {}, action = {}) => {
  switch(action.type) {
    case FETCH_USER_SUCCESS:
      return action.user
    default: return state;
  }
}

export default user;
3 条回复

© 汕尾市求知科技有限公司 | 粤ICP备19038915号 | 在线学员:103

Top