redux 异步中间件有什么意义呢?

当我想发送一个请求时,直接在fetch函数里写不就好了么,为什么要多一步中间件呢?

const mapDispatchToProps = ( dispatch )=>({

    fetchAndRenderArticle( articleName ){

        fetch(`http://localhost:3000/getFile?articleName=${articleName}`).then( res=> {

            return res.text();

        }).then( articleContent =>{

            dispatch({

                type:'fetchAndRenderArticle',         

                articleContent:articleContent

            });

        }).catch( err=>{

            console.log(err);

        });

    }

});


呼唤远方
浏览 1083回答 1
1回答

慕沐林林

异步中间件是用来编写异步Action的。其实你的问题更像为什么要用异步Action,请求封装成Action是为什么?Action统一管理触发,reducer统一管理接收,并且更改状态。这只是一种设计模式,降低代码耦合度。于是,你的问题,请求需要封装成异步Action,而异步Action依赖于异步中间件。这就是为什么需要redux异步中间件了。
打开App,查看更多内容
随时随地看视频慕课网APP