首页 文章

ngrx:调用reducers函数时是如何调用的?

提问于
浏览
5

我正在尝试使用ngrx库来管理我的应用程序状态 . 我已经浏览了许多ngrx文档和git页面 . 我知道有三个重要的概念:

  • 商店

  • 减速机和

  • 行动

Store是我们应用程序的单一数据源 . 因此,任何数据的修改或检索都是通过Actions完成的 . 我的问题是,当一个动作被发送到商店时到底发生了什么?它如何知道要调用哪个减速器?它是否解析了注册到商店的所有减速器?在这种情况下,可能会有多个具有相同名称的操作会发生什么?

提前致谢 .

2 回答

  • 5

    一张图片胜过千言万语...

    enter image description here

    enter image description here

    资料来源:Building a Redux Application with Angular2

    示例代码:ngrx-todo-app

    演示:Todo App using @ngrx/store and @ngrx/effects

  • 2

    我的问题是,当一个动作被发送到商店时到底发生了什么? All of the registered reducers get a chance to handle the action

    它如何知道要调用哪个减速器? All of the registered reducers get invoked. Try putting console.logs into all the reducers and you can see for yourself.

    它是否解析了注册到商店的所有减速器? Yes

    在这种情况下,可能会有多个具有相同名称的操作会发生什么? If you have multiple actions with the same name they would be treated the same. For example if I dispatched type "ADD" with payload 3 and then dispatched a different action called type "ADD" with payload 3 it would be the same thing.

    Ngrx并不那么聪明 . 假设我们有以下减速器:

    const redurs = {blog:BlogReducer,post:PostReducer,comment:CommentReducer}

    假设我发送'ADD_COMMENT' . 基本上BlogReducer将首先尝试处理它,然后是PostReducer,最后是CommentReducer . 排序取决于您如何指定上面的redurs对象 . 所以,如果我这样做:

    const redurs = {comment:CommentReducer,blog:BlogReducer,post:PostReducer}

    CommentReducer将是第一个尝试处理'ADD_COMMENT'的人 .

相关问题