简单介绍一下thunk,这是一个中间件,是解决redux异步问题产生的。我们都知道,在使用redux的时候,通过dispatch一个action 发生到reducer 然后传递给store修改状态 一系列都是同步的,那如果说我dispatch一个action 这个action帮我请求一下接口数据,你发现接口请求是异步的,没有办法等接口数据返回再传递给reducer 这个时候中间件就产生啦。 redux比较常用的中间件有 redux-saga、redux-thunk、redux-promise等 都是为了解决dispatch action异步处理问题

redux中间件 对redux应用实现异步

使用thunk等中间件可以帮助在 Redux 应用中实现异步性。可以将 thunk 看做 store 的 dispatch() 方法的封装器;我们可以使用 thunk action creator 派遣函数或 Promise,而不是返回 action 对象。 例如:正常请求接口完再使用dispatch去修改状态。但是如果想在dispath -> action里面执行异步操作 就需要thunk 注意,没有 thunk 的话,默认地是同步派遣。

redux-thunk 使用实例:

首先安装:yarn add redux-thunk

store.js

import { createStore, combineReducers, applyMiddleware } from 'redux';

import thunk from 'redux-thunk';

import {add, deleter} from './Reducers/TodoList';

// combineReducers 合并多个reducer

// applyMiddleware是redux提供了应用中间件的函数 只要应用了中间件 dispatch的流程就可以经过中间件了

// 例如以前是: dispatch -> action -> reducer -> store

// 现在是: dispatch -> action -> middleware -> reducer -> store

export default createStore(

combineReducers({add, deleter}),

applyMiddleware(thunk) // 应用thunk中间件

);

// 在对dispatch函数进行映射时 action creator 可以直接返回一个函数 不用直接返回action 这使得里面可以写异步操作 先去请求接口 在去dispatch一个action到reducer

// 当应用了thunk中间件时 action creator返回的函数都会默认传递一个dispatch的方法 然后再去dispatch action

const mapDispatchToProps = {

dispatchListAction: (res) => {

return {

type: FETCH_LIST,

payload: res

};

};

getList: () => {

return (dispatch) => {

fetch('http://jsonplaceholder.typicode.com/posts').then((res) => {

return res.json()

}).then(res => {

dispatch(mapDispatchToProps.dispatchListAction(res));

})

}

}

};

redux-thunk源码

源码仅仅只有10多行,虽然这有几行代码,但仍不失为是一个好的组件,简单就可以解决异步问题 有兴趣的可以去阅读一下源码 这里就不做源码剖析了

源码阅读的话应该先从applyMiddleware这个函数开始入手 然后方知thunk之精髓

来源参考:憧憬在 aoppp.com发布

精彩内容

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: