如何在redux中创建AJAX请求

前端之家收集整理的这篇文章主要介绍了如何在redux中创建AJAX请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
对于所有我知道,我必须在行动创建请求。如何使用行动中的承诺来提交请求?我得到的数据在行动。然后在reducer中创建新状态。在连接中绑定动作和缩减器。但我不知道如何使用promise的请求。

行动

import $ from 'jquery';
export const GET_BOOK = 'GET_BOOK';

export default function getBook() {
  return {
    type: GET_BOOK,data: $.ajax({
      method: "GET",url: "/api/data",dataType: "json"
    }).success(function(data){
      return data;
    })
  };
}

减速器

import {GET_BOOK} from '../actions/books';

const booksReducer = (state = initialState,action) => {
  switch (action.type) {
    case GET_BOOK:
      return state;
    default:
      return state;
  }
};

export default booksReducer;

容器
如何在容器中显示数据?

import React,{ Component,PropTypes } from 'react';
import { connect } from 'react-redux';
import getBook  from '../actions/books';
import Radium from 'radium';
import {Link} from 'react-router';

function mapStateToProps(state) {
  return {
    books: state.data.books,};
}

function mapDispatchToProps(dispatch) {
  return {
    getBooks: () => dispatch(getBook()),};
}

@Radium
@connect(mapStateToProps,mapDispatchToProps)
class booksPage extends Component {
  static propTypes = {
    getBooks: PropTypes.func.isrequired,books: PropTypes.array.isrequired,};

  render() {
    const {books} = this.props;
    return (
      <div>
        <Link to={`/authors`}><MUIButton style="flat">All Authors</MUIButton></Link>
        <ul>
          {books.map((book,index) =>
            <li key={index}>
              <Link to={`/book/${book.name}`}><MUIButton style="flat"><div class="mui--text-black mui--text-display4">
                "{book.name}"</div></MUIButton></Link>
              <Link to={`/author/${book.author}`}><MUIButton style="flat"><div class="mui--text-black mui--text-display4">
                {book.author}</div></MUIButton></Link>
            </li>
          )}
        </ul>
      </div>
    );
  }
}

export default booksPage;
因为你已经使用了redux,你可以应用redux-thunk中间件,它允许你定义异步动作。

安装&用法Redux-thunk

export function fetchBook(id) {
 return dispatch => {
   dispatch(setLoadingBookState()); // Show a loading spinner
   fetch(`/book/${id}`,(response) => {
     dispatch(doneFetchingBook()); // Hide loading spinner
     if(response.status == 200){
       dispatch(setBook(response.json)); // Use a normal function to set the received state
     }else { 
       dispatch(someError)
     }
   })
 }
}

function setBook(data) {
 return { type: 'SET_BOOK',data: data };
}
原文链接:https://www.f2er.com/ajax/160726.html

猜你在找的Ajax相关文章