gpt4 book ai didi

javascript - 服务器调用后更新状态?

转载 作者:行者123 更新时间:2023-12-03 02:51:13 26 4
gpt4 key购买 nike

在从服务器接收到一组新数据后,我对更新和从 reducer 返回正确的状态感到困惑。我实际上不明白服务器响应后要返回什么(如何更新状态)。为了能够更清楚地了解我的困惑:

举个例子:在一个待办事项应用程序上,我会有一个 reducer :

// imports..

export function todoReducer(state = [], action) {
switch (action.type) {
// some cases...

case todoActions.TODO_LOADED: {
return [
...state,
{
...action.payload
}
]
}

// some more cases...
default:
return state;
}
}

以及效果:

@Effect() todoList$: Observable<any> = this.action$
.ofType(todoActions.TODO_LOAD)
.switchMap(() => {
return this.http
.get('/rest/todo-list')
.map((todos: Todos) => new todoActions.TodoLoaded(todos))
.catch(err => Observable.of(new todoActions.TodoFailed(err)));
});

todoActions.TODO_LOAD被触发时,我显然会得到待办事项列表。到这里就清楚了。

但是,如果用户从 UI 中删除待办事项,我如何更新 reducer 中的状态?我会从我的组件中分派(dispatch)一个 todoActions.TodoRemove 操作,其中包含要删除的待办事项的 id...

对于经验:

@Effect() removeTodo$: Observable<any> = this.action$
.ofType(todoActions.TODO_REMOVE)
.switchMap((action : todoActions.TodoRemove) => {
return this.http
.delete(`/rest/todo-list/${action.payload['todoId']}`)
.map(() => {
// What kind of action should I apply here?
})
.catch(err => Observable.of(new todoActions.TodoFailed(err)));
});

所以问题是在服务器成功响应后我应该触发什么样的操作(假设我只得到 200)?

如果我再次触发todoActions.TODO_LOAD。它将列表与之前的状态合并,我将得到待办事项的两倍...

但是我们不应该改变状态...所以我不应该在每次加载新待办事项时刷新状态...对吧?

或者我只需要创建一个新的操作,例如 todoActions.TODO_REMOVE_SUCCESSED 并从服务器返回新的待办事项列表,而不带状态...例如:

case todoActions.TODO_REMOVE_SUCCESSED: {  
return [...action.payload ]
}

这会是反模式吗?

也许这是一个愚蠢的问题,但我不明白......

提前致谢!

最佳答案

我会尝试一个更标准、干净、简单的解决方案。还将解决您的重复问题并始终正确更新您的商店。

您需要 6 个操作:

import { Action } from '@ngrx/store';

/* App Models */
import { Todo } from './todo.model';

export const TODO_GET = '[Todo] get todo';
export const TODO_GET_SUCCESS = '[Todo] get todo success';
export const TODO_DELETE = '[Todo] delete todo';
export const TODO_DELETE_SUCCESS = '[Todo] delete todo success';
export const TODO_GET_BY_ID = '[Todo] get todo by id';
export const TODO_GET_BY_ID_SUCCESS = '[Todo] get todo by id success';

// Gets Todos from APIs
export class TodoGetAction implements Action {
readonly type = TODO_GET;
}

// Returns APIs fetched Todos
export class TodoGetSuccessAction implements Action {
readonly type = TODO_GET_SUCCESS;
constructor(public payload: Todo[]) {}
}

// Deletes a Todo given its string id
export class TodoDeleteAction implements Action {
readonly type = TODO_DELETE;
constructor(public payload: string) {}
}

// True -> Success, False -> Error
export class TodoDeleteSuccessAction implements Action {
readonly type = TODO_DELETE_SUCCESS;
constructor(public payload: Todo[]) {}
}

// Takes the id of the todo
export class TodoGetByIdAction implements Action {
readonly type = TODO_GET_BY_ID;
constructor(public payload: string) {}
}

// Returns todo by id
export class TodoGetByIdSuccessAction implements Action {
readonly type = TODO_GET_BY_ID_SUccess;
constructor(public payload: Todo) {}
}

export type All =
| TodoGetAction
| TodoGetSuccessAction
| TodoDeleteAction
| TodoDeleteSuccessAction
| TodoGetByIdAction
| TodoGetByIdSuccessAction;

然后你将拥有一个具有简单状态的 reducer ,其中包含一系列待办事项和由 id 选择的当前待办事项。我们在这里处理所有成功的操作,同时我们在效果中处理所有正常的操作:

import { createFeatureSelector } from '@ngrx/store';
import { createSelector } from '@ngrx/store';

/* ngrx */
import * as TodoActions from './todo.actions';

/* App Models */
import { Todo } from './todo.model';

// Get all actions
export type Action = TodoActions.All;

export interface TodoState {
todos: Todo[];
todoById: Todo;
}

// Initial state with empty todos array
export const todoInitialState: TodoState = {
todos: [],
todoById: new Todo({})
}

/* Selectors */
export const selectTodoState = createFeatureSelector<
TodoState
>('todo');
// Select all Todos
export const selectTodos = createSelector(
selectTodoState,
(state: TodoState) => state.todos
);
export const selectTodoByID = createSelector(
selectTodoState,
(state: TodoState) => state.todoById
);

export function todoReducer(
state: TodoState = todoInitialState,
action: Action
) {
switch (action.type) {
case TodoActions.TODO_GET_SUCCESS:
const oldTodos = state.todos;
// Add new todos to old ones
const newTodos = oldTodos.concat(action.payload);
// Cast to set to have only unique todos
const uniqueTodos = new Set(newTodos);
// Cast back to array to get an array out of the set
const finalTodos = Array.from(uniqueTodos);
return {
...state,
todos: [...finalTodos]
}
case TodoActions.TODO_DELETE_SUCCESS:
return {
...state,
todos: state.todos.filter( todo => return todo.id !== action.payload)
}
case TodoActions.TODO_GET_BY_ID_SUCCESS:
return {
...state,
todoById: state.todos.filter( todo => return todo.id === action.payload)[0]
}
default:
return state;
}
}

然后你将获得 3 个效果:

import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';
import { Store } from '@ngrx/store';

/** rxjs **/
import { mergeMap } from 'rxjs/operators/mergeMap';
import { catchError } from 'rxjs/operators/catchError';
import { map } from 'rxjs/operators/map';
import { of } from 'rxjs/observable/of';

/** ngrx **/
import * as TodoActions from './todo.actions';
import { AppState } from '../app-state.interface';

/** App Services **/
import { TodoService } from './province.service';

@Injectable()
export class TodoEffects {

@Effect()
getTodos$ = this.actions$.ofType(TodoActions.TODO_GET).pipe(
mergeMap(() => {
// I Imagine you can move your api call in such service
return this.todoService.getTodos().pipe(
map((todos: Todo[]) => {
return new TodoActions.TodoGetSuccessAction(todos);
}),
catchError((error: Error) => {
return of(// Handle Error Here);
})
);
})
);

@Effect()
deleteTodo$ = this.actions$.ofType(TodoActions.TODO_DELETE).pipe(
mergeMap((action) => {
return new TodoActions.TodoDeleteSuccessAction(action.payload);
})
);

@Effect()
getTodoByID$ = this.actions$.ofType(TodoActions.TODO_GET_BY_ID).pipe(
mergeMap((action) => {
return new TodoActions.TodoGetByIdSuccessAction(action.payload);
})
);

constructor(
private todoService: TodoService,
private actions$: Actions,
private store: Store<AppState>
) {}
}

最后,在您的 Todo 组件中,您可以发送和订阅更改,以便从商店中获取最新信息。当然,我假设您有一些方法可以通过 id 调度一个新的 GetTodoById 并将 todo 的 id 传递给它来触发研究,并且还有其他方法以相同的方式处理消除。您在商店中进行的每项修改都将反射(reflect)到通过选择器订阅的组件中的条目。

. . .

todos$: Observable<Todo[]>;
todoById$: Observable<Todo>;

constructor(private store: Store<AppState>) {
this.todos$ = this.store.select(selectTodos);
this.todo$ = this.store.select(selectTodoById);
}

ngOnInit() {
this.store.dispatch(new TodoActions.TodoGetAction);
}

关于javascript - 服务器调用后更新状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47849548/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com