You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
exportdefaultfunctioncreateStore(reducer,preloadedState,enhancer){if(typeofpreloadedState==='function'&&typeofenhancer==='undefined'){enhancer=preloadedStatepreloadedState=undefined}if(typeofenhancer!=='undefined'){if(typeofenhancer!=='function'){thrownewError('Expected the enhancer to be a function.')}returnenhancer(createStore)(reducer,preloadedState)}}
当我们只使用
redux
的时候,我们需要dispatch
的是一个action
对象。但是当我们使用redux-thunk
之后,我们dispatch
的是一个function
。redux-thunk
会自动调用这个function
,并且传递dispatch
方法作为其第一个参数。这样一来,我们就能在这个function
内根据我们的请求状态:开始请求,请求中,请求成功/失败,dispatch
我们期望的任何action
了,这也是为什么它能支持异步dispatch (action)
。1. 使用
我们先看看,在
reudx
中如何使用中间件:直接将thunk
中间件引入,作为applyMiddleware
的参数,然后传入createStore
方法中,就完成了store.dispatch()
的功能增强,这样就可以进行一些异步的操作了。其中applyMiddleware
是Redux
的一个原生方法,将所有中间件组成一个数组,依次执行,中间件多了可以当做参数依次传进去。一般来说,一个有效携带数据的
action
是如下这样的:加入
redux-thunk
后,action
可以是函数了,依据redux-thunk
的源码,我们可以看出如果传入的action
是函数,则返回这个函数的调用。如果传入的函数是一个异步函数,我们完全可以在函数调用结束后,获取必要的数据再次触发dispatch
,由此实现异步效果。参考文档
The text was updated successfully, but these errors were encountered: