美文网首页
redux-thunk 异步实现

redux-thunk 异步实现

作者: _贺瑞丰 | 来源:发表于2018-08-14 18:13 被阅读59次

    1.redux同步简介

    image.png

    2.thunk异步实现思路

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

    • dispatch发送的不再是纯js对象,而是一个函数
      !!!!在这个函数里面可以做各种异步任务!!!!!,做完了之后

    • 为了让store.dispatch能接受函数,需要使用中间件,即

    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')
    

    相关文章

      网友评论

          本文标题:redux-thunk 异步实现

          本文链接:https://www.haomeiwen.com/subject/ymdmbftx.html