redux默认支持同步操作,异步操作怎么办?Action发出以后,Reducer立即算出 State,这叫做同步;Action 发出以后,过一段时间再执行 Reducer,这就是异步。怎么才能Reducer 在异步操作结束后自动执行呢?这就要用到新的工具:中间件。中间件有很多,这里使用一个 Redux 官方出品的 中间件库:redux-thunk
使用redux-thunk
它支持函数返回,本质还是在在内部调用dispatch返回一个固定值对象
npm i -S redux-thunk
在createStore实例store中使用
import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
const store = createStore(
reducer,
applyMiddleware(thunk)
)
export default store
import { createStore, applyMiddleware, compose } from 'redux' // a(b(c(1,2,3))) => compose('a','b','c')(1,2,3) // 中间件 异常操作 返回function import thunk from 'redux-thunk' import reducer from './reducers/countReducer' /* function mym(store) { return function (next) { return function (action) { console.log('你好'); next(action) } } } */ // 自定义中间件 一般在公司中用它来记录日志 const mym = store => next => action => { console.log(action,store) next(action) } // 配置chrome中的redux扩展可视化操作 const composeEnhancers = typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose const enhancer = composeEnhancers( applyMiddleware(thunk, mym) ) export default createStore( reducer, enhancer )
// action一个要求,返回一个对象 {type payload} /* export const incr = () => { // 异步 回调 在回调中返回一个对象 此时action没有返回对象 return dispatch => { setTimeout(() => { dispatch({ type: 'incr', payload: 1 }) }, 2000); } } */ // 固定对象 不导出 私有函数 const incrAction = num => ({ type: 'incr', payload: num }) // 公有函数 export const incr = () => dispatch => { // 异步 回调 在回调中返回一个对象 此时action没有返回对象 setTimeout(() => { let num = 10 dispatch(incrAction(num)) }, 2000); }