ngrxstore

xiaoxiao2021-02-28  47

简介

ngrx/store:保存了ReduxAPI的核心概念,使用RxJS扩展的Redux实现。使用可观察对象来简化了监听事件的订阅等操作。

dispatcher,reducer,state都是基于BehaviorSubject的 BehaviorSubject:储存着要发射给消费者的最新的值。无论何时一个新的观察者订阅它,都会立即接受到这个来自BehaviorSubject的”当前值”。

创建一个应用存储的接口可以便于理解reducers是如何用于应用的。如果需要额外的功能,存储可以扩展新的键值对来容纳更新的模型。

store的select方法:定义当state改变时,state的哪一部分应该被返回,返回一个Observable对象。

一个小例子:

// The "items" reducer performs actions on our list of items export const items = (state: any = [], {type, payload}) => { switch (type) { default: return state; } }; // The "selectedItem" reducer handles the currently selected item export const selectedItem = (state: any = null, {type, payload}) => { switch (type) { default: return state; } }; export interface AppStore { items: Item[]; selectedItem: Item; } this.videos$ = this.store.select(state => state.videos);

使用store作为状态管理的优点

集中管理state性能 使用onPush的变更检测策略;且可直接在模板中使用observable对象易于测试 因为reducer是纯函数易于调试 便于观察状态的改变,以及何时哪里为什么出错; middleware???

工作流程

Created with Raphaël 2.1.0 ngrx/store工作流程 展示组件上用户交互 是否为异步操作? 容器组件调用服务类 服务类调用dispatch方法 使用reducer生成新的state 模板中使用async的变量,自动重新渲染;store自动调用observer 等待进一步的用户交互 容器组件直接调用dispatch方法 yes no

ngrx/store使用步骤

安装相应npm包

npm install ngrx/store ngrx/core --save-dev

定义store模块

创建action与reducer连接reducer与store模块在组件或服务中使用reducer
转载请注明原文地址: https://www.6miu.com/read-81645.html

最新回复(0)