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代 ...
随机推荐
- Appium自动化测试3之获取apk包名和launcherActivity后续
接着“Appium自动化测试3之获取apk包名和launcherActivity”章节介绍 测试脚本 1.测试脚本如下: # -*- coding:utf-8 -*- import os, time, ...
- Juicer——a fast template engine
https://blog.csdn.net/yutao_struggle/article/details/79201688 当前最新版本: 0.6.8-stable Juicer 是一个高效.轻量的前 ...
- galera安装之编译安装xtrabackup 2.2.11
----1.编译安装percona-xtrabackup yum -y install cmake gcc gcc-c++ libaio libaio-devel automake autoconf ...
- 《从零开始学Swift》学习笔记(Day 66)——Cocoa Touch设计模式及应用之通知机制
原创文章,欢迎转载.转载请注明:关东升的博客 通知(Notification)机制是基于观察者(Observer)模式也叫发布/订阅(Publish/Subscribe)模式,是 MVC( 模型-视图 ...
- 160520、MyBatis的几种批量操作
MyBatis中批量插入 方法一: <insert id="insertbatch" parameterType="Java.util.List"> ...
- Spring---Bean的继承与依赖
Spring 允许继承 bean 的配置(通过Bean的parent属性来指定,例如parent=”teacher“), 被继承的 bean 称为父 bean. 继承这个父 Bean 的 Bean ...
- Struts2中解决表单重复提交
3. 表单的重复提交问题 1). 什么是表单的重复提交 > 在不刷新表单页面的前提下: >> 多次点击提交按钮 >> 已经提交成功, 按 "回退" ...
- C语言实现链表中结构体嵌套
1.首先,定义两个结构体,一个用于定义链表,一个用于定义数据 // 定义数据相关的结构体 typedef struct Student{ int stu_id; ]; }Stu; // 定义链表相关的 ...
- echart绑定点击事件
实例页面:http://echarts.baidu.com/echarts2/doc/example/event.html option = { tooltip : { trigger: 'axis' ...
- Servlet------>ServletConfig和ServletContext
原理图: 之一--------->servletConfig 有些时候,有些参数不适合写死,而且初始化servlet要用,可以通过这个头来调用servletConfig 例如:serlet数据库 ...