在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 }>());

更新 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);
}

在组件中分派 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 }));
  }
}

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

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

09-14 09:13