• NgRx不使用effect,怎样将数据存入store


    在ngrx中,如果你不想使用 @Effect 来处理副作用(如异步操作),你可以直接在 reducer 中将数据存入 store。以下是如何实现的一般步骤:

    创建一个 Action 类:首先,创建一个 Action 类来描述你要执行的操作,例如添加数据到 store。

    // my-actions.ts
    import { createAction, props } from '@ngrx/store';
    
    export const addData = createAction('[My Component] Add Data', props<{ data: any }>());
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    更新 reducer:在你的 reducer 中,添加一个处理该 Action 的 case,以将数据存入 store。

    // my-reducer.ts
    import { createReducer, on } from '@ngrx/store';
    import { addData } from './my-actions';
    
    export const initialState = {
      data: null,
    };
    
    const myReducer = createReducer(
      initialState,
      on(addData, (state, { data }) => {
        return { ...state, data };
      })
    );
    
    export function reducer(state, action) {
      return myReducer(state, action);
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在组件中分派 Action:在你的组件中,当你要将数据添加到 store 时,分派上面定义的 Action。

    // my-component.ts
    import { Component } from '@angular/core';
    import { Store } from '@ngrx/store';
    import { addData } from './my-actions';
    
    @Component({
      selector: 'app-my-component',
      template: `
        <button (click)="addDataToStore()">Add Data to Store</button>
      `,
    })
    export class MyComponent {
      constructor(private store: Store) {}
    
      addDataToStore() {
        const dataToAdd = // 数据的来源,例如从表单中获取
        this.store.dispatch(addData({ data: dataToAdd }));
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    这样,当你点击 “Add Data to Store” 按钮时,addData Action 将被分派,并且 reducer 将根据该 Action 更新 store 中的数据。

    这是一个简单的示例,展示了如何在ngrx中将数据存入 store,而不使用 @Effect。如果你需要执行更复杂的操作,例如从服务器获取数据或处理其他异步操作,可能需要考虑使用 @Effect 来处理这些副作用。

  • 相关阅读:
    Centos7 Redis安装
    Prometheus监控的搭建(ansible安装——超详细)
    python工具方法 47 基于paddleseg将目标检测数据升级为语义分割数据
    dubbo-admin安装
    推荐一款适合科技行业的CRM系统
    【Cucumber】关于BDD自然语言自动化测试的语法总结
    js中HTMLCollection如何循环
    网络编程套接字 | 预备知识
    基于前后端分离的增删改查
    muduo第二章死锁问题
  • 原文地址:https://blog.csdn.net/weixin_43160662/article/details/132867094