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代 ...
随机推荐
- 转载 --iOS实用小技巧(2)-生成txt文本
//不论是创建还是写入只需调用此段代码即可 如果文件未创建 会进行创建操作 - (void)writeToFileWithTxt:(NSString *)string{ dispatch_async( ...
- Invalid property 'driverClassName' of bean class [com.mchange.v2.c3p0.ComboPooledDataSource]
spring配置文件中配置c3p0错误,错误原因在于c3p0连接池与DBCP连接池在驱动.连接.数据库用户名这些属性名称的差别
- 第七篇:使用 CUDA 进行计算优化的两种思路
前言 本文讨论如何使用 CUDA 对代码进行并行优化,并给出不同并行思路对均值滤波的实现. 并行优化的两种思路 思路1: global 函数 在 global 函数中创建出多个块多个线程对矩阵每个元素 ...
- git+sourcetree创建仓库
1.git上创建版本库 2.安装sourcetree 3.创建空目录 我本地空目录为D:/shenghuojia 4.打开sourcetree,点击clone/new ,选择clone reposit ...
- sql语句中left join、right join 以及inner join之间的使用与区别
sql语句中left join.right join 以及innerjoin之间的使用与区别 left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录 right join( ...
- JS中的call、apply、bind 用法解疑
JS中的caller arguments.callee call apply bind方法 一.call()和apply()方法 1.方法定义 call方法: 语法:call([thisObj ...
- CodeForces 24A Ring road(dfs)
A. Ring road time limit per test 2 seconds memory limit per test 256 megabytes input standard input ...
- Storm-源码分析-Topology Submit-Supervisor
mk-supervisor (defserverfn mk-supervisor [conf shared-context ^ISupervisor isupervisor] (log-message ...
- Python面象对象与类
# -*- coding: utf-8 -*- # @Date: 2017-08-26 # @Original: from collections import namedtuple from col ...
- 数字货币量化分析报告_20170905_P
[分析时间]2017-09-05 16:36:46 [数据来源]中国比特币 https://www.chbtc.com/ef4101d7dd4f1faf4af825035564dd81聚币网 http ...