redux-thunk 异步实现

2018-08-14  本文已影响59人  _贺瑞丰

1.redux同步简介

image.png

2.thunk异步实现思路

从action发出到store接受用reducer处理的过程中,没有可以插入异步的地方。
我们拦截action的发送,在dispatch的过程中,dispatch一个异步函数,异步函数执行完成后才dispatch一个同步的action,送达store.

const store = createStore(
    reducer,
    applyMiddleware(thunk)
)

中间件的具体原理

store.dispatch进行如下改造

function incrementAsync() {
    setTimeout(()=>{store.dispatch({type:'INCREMENT'})},1000 )
}
//应用层
 ReactDOM.render(
    <Counter
      value={store.getState()}
      onIncrementAsync={() => store.dispatch(incrementAsync)}
    />,
    document.getElementById('root')
上一篇下一篇

猜你喜欢

热点阅读