gpt4 book ai didi

angular - 在 NgRx Effect 中重新填充状态

转载 作者:太空狗 更新时间:2023-10-29 18:27:31 26 4
gpt4 key购买 nike

我的 JSON 在我看来最初是一个 JSON.stringify(state) 并且需要将该 JSON 字符串添加回状态以更新应用程序。 (Angular 和 NgRx/Redux 的新手)。

我有这样的效果(我可能做错了):

@Effect({ dispatch: false })
upState$ = this.actions$.pipe(
ofType(WorkspaceActionTypes.UpState),
withLatestFrom(this.store.select(fromSpace.getState)),
tap(([empty, space]) => {
console.log(JSON.stringify(space));

var json = "my json file in string form";
space = json;
})

);

json 不能从字符串到类型 State。

更新:

查看评论中的链接后,我是否应该创建一个效果来调用一个 Action ,该 Action 调用一个 reducer 来更新状态?我从链接中看到了这个,但还不确定如何使用它:

@Effect() 
createArticle$: Observable<Action> = this.actions$
.ofType<fromActions.CreateAction>(fromActions.CREATE)
.map(action => action.payload)
.mergeMap(article =>
this.articleService.createArticle(article)
.map(res => new fromActions.CreateSuccessAction(res))
.catch(error => of(new fromActions.CreateFailureAction(error)))
);

最佳答案

你能为你的reducer添加代码吗?您应该在效果中反序列化您的 JSON 字符串。然后,效果应该派发一个被你的 reducer 捕获的 Action 。然后你的 reducer 更新状态(这是 redux/ngrx 中唯一允许这样做的函数)。它通常看起来像:

switch(action.type){

//... other cases
case CreateSuccessAction:
return {...state, article: action.payload} // <-- or whatever the shape of your state looks like.
// more other cases...

}

注意:我不知道您使用的是哪个版本的 ngrx,也不知道您使用的是枚举状态类型还是常量字符串。但基本上,您可以在开关和案例中过滤操作类型(最新版本具有减少样板的创建者功能)。

Ngrx/Redux 基本上是这样工作的: Action 由应用程序触发,并由 reducer 捕获。 reducer 是一个纯函数,可以不可变地更新存储。因为 reducer 不应该有副作用,所以 effects 模块会处理诸如日志记录、数据库内容、文件 i/o... 或 JSON 序列化/反序列化之类的事情。因此,将您的 JSON 放入操作负载中,分派(dispatch)它,然后让 reducer 进行状态更新。

此外,作为旁注。如果您不需要 effect 中的 observables,我认为使用 switchMap 而不是 mergeMap 更安全。这样,效果会取消所有订阅,转而支持新的可观察对象。避免可能的内存泄漏

关于angular - 在 NgRx Effect 中重新填充状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57562952/

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