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代 ...
随机推荐
- MySQL单列索引和组合索引的选择效率与explain分析
一.先阐述下单列索引和组合索引的概念: 单列索引:即一个索引只包含单个列,一个表可以有多个单列索引,但这不是组合索引. 组合索引:即一个索包含多个列. 如果我们的查询where条件只有一个,我们完全可 ...
- c#后台修改前台DOM的css属性示例代码
<div id = 'div1' runat="server">haha</div> ----------- 后台代码中这样调用 div1.Style[&q ...
- sgu 326(经典网络流构图)
题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=13349 题目大意:有N个球队在同一个赛区,已知他们胜利的场数,还剩 ...
- python2迁移python3的问题
▌使用 pathlib 模块来更好地处理路径 pathlib 是 Python 3默认的用于处理数据路径的模块,它能够帮助我们避免使用大量的 os.path.joins语句: from pathlib ...
- SurvivalShooter学习笔记(九.游戏暂停、结束)
这里先补充一个得分管理器: 玩家得分设置成一个静态变量: public class ScoreManager : MonoBehaviour { public static int score; // ...
- 苹果发布【新开发语言】Swift
Swift is a multi-tenant, highly scalable and durable object storage system that was designed to stor ...
- OpenSSL创建私有CA
1.编辑/etc/pki/tls/openssl.cnf [ CA_default ] dir = /etc/pki/CA # 工作目录certs ...
- 三分搜索-ZOJ LightBulb
开始算法基础学习的第一天 今天学习的内容是三分搜索 相对来说很基础的内容(还是觉得脑子不够用) 三分搜索主要用于凸函数查找极大值. (盗个图) 如图所示 若要查找该函数的最大值 可以考虑和二分法一样的 ...
- MySQL安装时出现Apply Security Settings错误的解决办法
windows版mysql安装执行程序下载地址: https://dev.mysql.com/downloads/file/?id=473605 点击下面的No thanks, just start ...
- CEF3 HTML5 audio标签为什么不能播放mp3格式的音频文件
CEF3 HTML5 audio标签 为什么不能播放mp3格式的音频文件 原因略. 解决方法: 找一个最新版的chrome ,我用的是24版本.路径 C:\Documents and Sett ...