1、the simple sample

action: 事实上,只是返回个一个至少包含type的对象{ },用于reducer接收。

import {RECEIVE_DATA} from "constant/ActionType";
import MessageService from "service/demo-service/MessageService"; const _messageService = new MessageService(); function receiveData(data) {
return {
type: RECEIVE_DATA,
list: data
}
} export function fetchData() {
return (dispatch) => {
_messageService.getMessage().then(res => {
dispatch(receiveData(res.data))
})
}
}

reducer:对应某个actionType有相应的数据返回

import {RECEIVE_DATA} from "constant/ActionType";

const initialState = {
message: []
}; const MessageReducer = function (state = initialState, action) {
switch (action.type) {
case RECEIVE_DATA:
return {message: action.list};
default:
return state;
}
};
export default MessageReducer;

use:

const mapStateToProps = state => {
return {
messageList: state.MessageReducer.message
}
};
const mapDispatchToProps = {
fetchMessageList: fetchData
};
componentDidMount() {
this.props.fetchMessageList();
}

2、Async Action Helpers

// status constants
export const REQUEST = 'request';
export const SUCCESS = 'success';
export const FAILURE = 'failure'; export const createAsyncAction = (type, promiseCreator) => {
return () => (dispatch, getState) => { dispatch({ type, readyState: REQUEST }); const promise = promiseCreator();
return promise.then(
data => {
dispatch({ type, readyState: SUCCESS, data });
},
error => {
dispatch({ type, readyState: FAILURE, error });
}
);
};
};

use:

function latestPostsRequest() {
return fetch(`https://www.reddit.com/latest.json`)
.then(
response => response.json(),
error => console.log('An error occured.', error)
)
} const FETCH_LATEST_POSTS = 'Actions/Posts/FetchLatest';
export const fetchLatestPosts = createAsyncAction(FETCH_LATEST_POSTS, latestPostsRequest);

result:

import { fetchLatestPosts } from '../actions/posts';

// in some component...
dispatch(fetchLatestPosts);
// immediately:
// { type: 'Actions/Posts/FetchLatest', readyState: 'request' } // after success:
// {
// type: 'Actions/Posts/FetchLatest',
// readyState: 'success',
// data: (some blob of json data from the api)
// }

3、More sophisticated actions: Args and Thunks

export const createAsyncAction = (type, promiseCreator) => {
// get hash of args to pass through to promise creator
return (args = {}) => (dispatch, getState) => { dispatch({ args, type, readyState: REQUEST }); // pass args through
let promise = promiseCreator(args); // handle thunk-style promises
if (typeof promise === 'function') {
promise = promise(dispatch, getState);
} return promise.then(
data => {
dispatch({ args, type, readyState: SUCCESS, data });
},
error => {
dispatch({ args, type, readyState: FAILURE, error });
}
);
};
};

use:

import { createAsyncAction } from 'helpers/async';
import fetch from 'isomorphic-fetch' // (pretend for a moment that such an action exists)
import { navigate, SIGN_IN } from 'actions/navigation'; // takes args: { subreddit }
function postsWithLikesRequest({ subreddit }) {
// returns a 'thunk promise' that uses dispatch and getState
return function(dispatch, getState) {
const userId = getState().userId; if(!userId) {
// we have the dispatch function in our async action!
dispatch(navigate(SIGN_IN))
} else {
return fetch(`https://www.reddit.com/r/${subreddit}.json?likes=true&userId=${userId}`)
.then(
response => response.json(),
error => console.log('An error occured.', error)
)
}
}
} const FETCH_POSTS_WITH_LIKES = 'Actions/Posts/FetchWithLikes';
export const fetchPostsWithLikes = createAsyncAction(FETCH_POSTS_WITH_LIKES, postsWithLikesRequest)

async reducer:

// helpers/async.js
import { combineReducers } from 'redux'; export const createAsyncReducer = (type) => {
const loading = (state = false, action) => {
if (action.type === type) {
return action.readyState === REQUEST;
}
return state;
}; const data = (state = null, action) => {
if (action.type === type) {
return action.data;
}
return state;
}; const error = (state = null, action) => {
if (action.type === type) {
return action.error;
}
return state;
}; return combineReducers({ loading, data, error });
};

use async reducer:

import { createAsyncReducer } from 'helpers/async';
import { FETCH_LATEST_POSTS } from 'actions/posts'; //
// Here's the reducer we can create with the helper
//
export const latestPosts = createAsyncReducer(FETCH_LATEST_POSTS); //
// It's functionally equivalent to writing all this:
//
export function latestPosts(state = { loading: false, data: null, error: null }, action) {
if(action.type === FETCH_LATEST_POSTS) {
switch(action.readyState) {
case 'request':
return { loading: true, data: null, error: null };
case 'success':
return { loading: false, data: action.data, error: null };
case 'failure':
return { loading: false, data: null, error: action.error };
}
}
return state;
}

5、More configuration

The naive reducer returned by the simple createAsyncReducerfunction above is pretty useful for simple data fetches, but we often want to do more than just store the data from a request.

The actual createAsyncReducer function we use supports swapping in reducers that can respond to different actions or handle the request actions differently.

import {combineReducers} from "redux";
import {FAILURE, REQUEST, SUCCESS} from "constant/ActionType"; export const asyncReducerHelper = (type, reducers = {}) => {
let defaultReducers = {
loading: (state = false, action) => {
if (action.type === type) {
return action.readyState === REQUEST;
}
return state;
},
data: (state = null, action) => {
if (action.type === type && action.readyState === SUCCESS) {
return action.data;
}
return state;
},
error: (state = null, action) => {
if (action.type === type && action.readyState === FAILURE) {
return action.err;
}
return state;
},
}; return combineReducers(Object.assign({}, defaultReducers, reducers));
};

use:

import { createAsyncAction, createAsyncReducer } from 'helpers/async';

// I'm using the fetch api here, but you can substitute any http request libarary.
// For more about the fetch api: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
const postsRequest = (subreddit) => {
return fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then(
response => response.json(),
error => console.log('An error occured.', error)
)
} const FETCH_POSTS = 'Actions/Posts/Fetch';
// async action
export const fetchPosts = createAsyncAction(FETCH_POSTS, postsRequest);
// async reducer with shape { loading, data, error }
export const posts = createAsyncReducer(FETCH_POSTS);

react-redux: async promise的更多相关文章

  1. 在react+redux+axios项目中使用async/await

    Async/Await Async/Await是尚未正式公布的ES7标准新特性.简而言之,就是让你以同步方法的思维编写异步代码.对于前端,异步任务代码的编写经历了 callback 到现在流行的 Pr ...

  2. react+redux教程(五)异步、单一state树结构、componentWillReceiveProps

    今天,我们要讲解的是异步.单一state树结构.componentWillReceiveProps这三个知识点. 例子 这个例子是官方的例子,主要是从Reddit中请求新闻列表来显示,可以切换reac ...

  3. react+redux教程(六)redux服务端渲染流程

    今天,我们要讲解的是react+redux服务端渲染.个人认为,react击败angular的真正“杀手锏”就是服务端渲染.我们为什么要实现服务端渲染,主要是为了SEO. 例子 例子仍然是官方的计数器 ...

  4. react+redux教程(一)connect、applyMiddleware、thunk、webpackHotMiddleware

    今天,我们通过解读官方示例代码(counter)的方式来学习react+redux. 例子 这个例子是官方的例子,计数器程序.前两个按钮是加减,第三个是如果当前数字是奇数则加一,第四个按钮是异步加一( ...

  5. 实例讲解基于 React+Redux 的前端开发流程

    原文地址:https://segmentfault.com/a/1190000005356568 前言:在当下的前端界,react 和 redux 发展得如火如荼,react 在 github 的 s ...

  6. 一个 React & Redux的目录树

    |-----------------------------------------| | | | React & Redux | | | |------------------------- ...

  7. 使用react+redux+react-redux+react-router+axios+scss技术栈从0到1开发一个applist应用

    先看效果图 github地址 github仓库 在线访问 初始化项目 #创建项目 create-react-app applist #如果没有安装create-react-app的话,先安装 npm ...

  8. webpack+react+redux+es6开发模式

    一.预备知识 node, npm, react, redux, es6, webpack 二.学习资源 ECMAScript 6入门 React和Redux的连接react-redux Redux 入 ...

  9. react+redux官方实例TODO从最简单的入门(6)-- 完结

    通过实现了增-->删-->改-->查,对react结合redux的机制差不多已经了解,那么把剩下的功能一起完成吧 全选 1.声明状态,这个是全选状态 2.action约定 3.red ...

  10. react+redux官方实例TODO从最简单的入门(1)-- 前言

    刚进公司的时候,一点react不会,有一个需求要改,重构页面!!!完全懵逼,一点不知道怎么办!然后就去官方文档,花了一周时间,就纯react实现了页面重构,总体来说,react还是比较简单的,由于当初 ...

随机推荐

  1. path的join和resolve的使用区别

    文章目录   1.连接路径:path.join([path1][, path2][, ...]) 2.路径解析:path.resolve([from ...], to) 3.对比 1.连接路径:pat ...

  2. 推荐系统第2周--itemCF和userCF

    推荐系统分类 基于应用领域分类:电子商务推荐,社交好友推荐,搜索引擎推荐,信息内容推荐基于设计思想:基于协同过滤的推荐,基于内容的推荐,基于知识的推荐,混合推荐基于使用何种数据:基于用户行为数据的推荐 ...

  3. 批量编译目录下文件的Makefile

    1.多C文件生成各自可执行文件的Makefile如果一个目录下有很多C文件,且每个C文件都能生成一个独立的可执行文件,那么想全编译这些C文件并生成各作的可执行文件,在该目录下编写一个Makefile文 ...

  4. Vue.js——框架

    一.什么是VUE vue 是一个构建用户界面的javascript框架 特点:轻量,高效 特性:双向数据绑定,数据驱动视图 二.vue的使用 1.引入vue.js <script src=vue ...

  5. 如何判断某String是否经过urlEncoder.encode过

    import java.util.BitSet; public class UrlEncoderUtils { private static BitSet dontNeedEncoding; stat ...

  6. javascript 中的比较大小,兼 typeof()用法

    javascript中的排序: 1.不同类型 比 类型 (字符串 > 数字)   2.同类型:(字符串  比 按字母顺序 )(数字 比 大小) 测试: <!DOCTYPE html> ...

  7. hadoop19---动态代理

    Action调用service里面的方法,动态代理:改变方法的实现在方法前后加逻辑不是加新方法. 在学习Spring的时候,我们知道Spring主要有两大思想,一个是IoC,另一个就是AOP,对于Io ...

  8. Mybatis中trim的使用

    trim标记是一个格式化的标记,可以完成set或者是where标记的功能,如下代码: 1. select * from user <trim prefix="WHERE" p ...

  9. 利用同步网盘搭建个人或团队SVN服务器

    这篇文章是以前写的,现在强烈推荐两个站.1.http://git.oschina.com 2.http://www.coding.net. 推荐理由:1.可创建私有项目.2.免费稳定.3.VS2013 ...

  10. 使用axis2构建webservice

    axis2是可以实现webservice的一个插件,使用这个插件可以发布webservice 1:可以使用这个插件来发布webservice,可以看网址:http://clq9761.iteye.co ...