React:快速上手(7)——使用中间件实现异步操作
React:快速上手(7)——使用中间件实现异步操作
本文参考链接:Stack Overflow
redux-thunk
我们使用store.dispath进行派发时,只能传递一个普通对象进去,如下:
store.dispatch({ type: 'INCREMENT' })
但是,在使用redux-thunk中间件后,我们就可以传递一个函数进去
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk' const store = createStore(
reducer,
applyMiddleware(thunk)
) store.dispatch(function (dispatch) {
// ... which themselves may dispatch many times
dispatch({ type: 'INCREMENT' })
dispatch({ type: 'INCREMENT' })
dispatch({ type: 'INCREMENT' }) setTimeout(() => {
// ... even asynchronously!
dispatch({ type: 'DECREMENT' })
}, 1000)
})
启用此中间件后,如果您dispatch一个函数,Redux Thunk中间件会将dispatch作为参数传进该函数中去。在这个函数中,我们派发了多个action,甚至可以异步执行一些操作,比如延迟1000ms,派发action。那我们执行异步操作,就是通过这个中间件来实现的。
Action Creator
我们最好把action封装到函数中,即(Action Creater),来提高灵活性以及防止我们拼写错误。对于对象,我们可以直接如下写:
function showNotification(id, text) {
return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
return { type: 'HIDE_NOTIFICATION', id }
}
那么这样一个函数式的action,我们也可以将其封装到一个函数中,它返回一个函数式的action
let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
return function (dispatch) {
const id = nextNotificationId++
dispatch(showNotification(id, text)) setTimeout(() => {
dispatch(hideNotification(id))
}, 5000)
}
}
那么,我们在调用它的时候是需要手动传入一个dispatch的。
showNotificationWithTimeout('You just logged in.')(this.props.dispatch)
如果启用了Redux Thunk中间件,则只要你尝试dispatch函数而不是对象,中间件就会使用调度方法本身作为第一个参数来调用该函数,也就是我们可以这样写:
// component.js
this.props.dispatch(showNotificationWithTimeout('You just logged in.'))
配合React Redux的connect
Redux可以自动识别出这样的“特殊”Action Creator(我们称之为Thunk Action Creator),我们现在可以在任何我们使用常规动作创建者的地方使用它们。例如,我们可以将它们与connect()一起使用:
// actions.js function showNotification(id, text) {
return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
return { type: 'HIDE_NOTIFICATION', id }
} let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
return function (dispatch) {
const id = nextNotificationId++
dispatch(showNotification(id, text)) setTimeout(() => {
dispatch(hideNotification(id))
}, 5000)
}
} // component.js import { connect } from 'react-redux' // ... this.props.showNotificationWithTimeout('You just logged in.') // ... export default connect(
mapStateToProps,
{ showNotificationWithTimeout }
)(MyComponent)
在thunk中获取状态
Redux Thunk提供了一种方法来获取Redux store的state。除了dispatch之外,它还将getState作为第二个参数传递给您从thunk action creator返回的函数。这让thunk读取store的当前state。
let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
return function (dispatch, getState) {
// Unlike in a regular action creator, we can exit early in a thunk
// Redux doesn’t care about its return value (or lack of it)
if (!getState().areNotificationsEnabled) {
return
} const id = nextNotificationId++
dispatch(showNotification(id, text)) setTimeout(() => {
dispatch(hideNotification(id))
}, 5000)
}
}
React:快速上手(7)——使用中间件实现异步操作的更多相关文章
- 官方 React 快速上手脚手架 create-react-app
此文简单讲解了官方 React 快速上手脚手架的安装与介绍. 1. React 快速上手脚手架 create-react-app 为了快速地进行构建使用 React 的项目,FaceBook 官方发布 ...
- React:快速上手(6)——掌握React Router
React:快速上手(6)——掌握React Router 引入Router 安装 npm install react-router-dom 基础组件 React Router中有三种类型的组件:路由 ...
- React:快速上手(5)——掌握Redux(2)
React:快速上手(5)——掌握Redux(2) 本文部分内容参考阮一峰的Redux教程. React-Redux原理 React-Redux运行机制 我觉得这张图清楚地描述React-Redux的 ...
- React:快速上手(4)——掌握Redux(1)
React:快速上手(4)——掌握Redux 引入Redux 混乱的state管理 随着 JavaScript 单页应用开发日趋复杂,JavaScript 需要管理比任何时候都要多的 state (状 ...
- React:快速上手(3)——列表渲染
React:快速上手(3)——列表渲染 使用map循环数组 了解一些ES6 ES6, 全称 ECMAScript 6.0 ,是 JaveScript 的下一个版本标准,2015.06 发版.ES6 主 ...
- React:快速上手(2)——组件通信
React:快速上手(2)——组件通信 向父组件传递数据 父组件可以通过设置子组件的props属性进行向子组件传值,同时也可以传递一个回调函数,来获取到子组件内部的数据. 效果演示 子组件是输入框,父 ...
- React:快速上手(1)——基础知识
React:快速上手(1)——基础知识 React(有时叫React.js或ReactJS)是一个为数据提供渲染为HTML视图的开源JavaScript库,用于构建用户界面. JSX.元素及渲染 1. ...
- React:快速上手(8)——前后端分离的跨域访问与会话保持
React:快速上手(8)——前后端分离的跨域访问与会话保持 跨域访问 跨域是指从一个域名的网页去请求另一个域名的资源.比如从http://www.baidu.com/ 页面去请求http://www ...
- react快速上手二(使用JSX语法)
前提: 下载依赖,配置 cnpm i babel-preset-react -D JSX语法的本质: 还是以 React.createElement 的形式来实现的,并没有直接把 用户写的 HTML代 ...
随机推荐
- 转:Socket服务器整体架构概述
Socket服务器主要用于提供高效.稳定的数据处理.消息转发等服务,它直接决定了前台应用程序的性能.我们先从整体上认识一下Socket服务器,Socket服务器从架构上一般分为:网络层.业务逻辑层.会 ...
- easyui上次图片
easyuiForm提交: 前台代码: <form id="importFileForm" method="post" enctype="mul ...
- Linq------错误: Unable to determine the principal end of an association between the types
[Table("bma_stores")] public class Store { //加上即可 [Required] public virtual Product Produc ...
- 第七篇:使用 CUDA 进行计算优化的两种思路
前言 本文讨论如何使用 CUDA 对代码进行并行优化,并给出不同并行思路对均值滤波的实现. 并行优化的两种思路 思路1: global 函数 在 global 函数中创建出多个块多个线程对矩阵每个元素 ...
- Linux Kernel 4.7版本发布
导读 在经历了长达一周的惬意假日时光,大神Linus Torvalds宣布面向所有GNU/Linux操作系统发布Linux Kernel 4.7.Linux 4.7内核的研发历经2个多月,自今年5月2 ...
- webpack配置(一)
这里再配置的时候走了些弯路,现在,把配置前的准备工作做好很重要: 首先,安装node.js,当然,npm也就有了: 其次,安装xampp,主要是为了配置Apache: 安装好后,xampp---htd ...
- 基于 Golang 的 xls 读取类库:xls
Golang 编写的 xls 读取类库,能够实现 xls 表格的读取功能 func (w *WorkBook) ReadAllCells() (res [][]string) { for _, she ...
- 1455: 罗马游戏[左偏树or可并堆]
1455: 罗马游戏 Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 1861 Solved: 798[Submit][Status][Discuss] ...
- 【黑金原创教程】【Modelsim】【第五章】仿真就是人生
声明:本文为黑金动力社区(http://www.heijin.org)原创教程,如需转载请注明出处,谢谢! 黑金动力社区2013年原创教程连载计划: http://www.cnblogs.com/al ...
- js 中的变量声明提前总结
一.var 声明 ES6之前,js 中声明变量基本上用 var 关键字: 1.如果访问未声明的变量,会报错:ReferenceError 2.声明了未赋值,值为 undefined,跟前面的报错是两回 ...