Redux:为什么我们需要动作? [英] Redux: Why do we need actions?

查看:79
本文介绍了Redux:为什么我们需要动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与 NgRx 合作实施 Redux.我试图理解 redux 模式.为什么我们需要调度一个动作?为什么我们不能直接从下面的服务代码中调用 userReducer 函数传递正确的动作?谢谢!

I'm working with NgRx to implement Redux. I'm trying to understand the redux pattern. Why do we need to dispatch an action? Why can't we just call the userReducer function directly from the service code below passing the correct action? Thanks!

服务代码:

this.store.dispatch(new userActions.SetName({bob"})

user.action.ts:

user.action.ts:

    readonly type = UserActionTypes.SET_NAME
    constructor(public payload: string) { }
    }

user.reducer.ts:

user.reducer.ts:

export function userReducer(
   state: UserState = BEGINNING_STATE
   action: UserActions
)
switch(action.type) {
case UserActionTypes.SET_NAME:
   return {
      ...state,
      Name: state.Name
   }
}

推荐答案

你分开表明发生了什么"(action) 来自如果 X 发生就这样做"(减速器/中间件).如果您直接调用 reducer,那么您就没有这种分离,因此,如果您重构一个将 INCREMENT 分派到执行一个特定 reducer 的按钮的按钮,您只需将代码更改为具有一个按钮,该按钮在单击时表示 INCREMENT 碰巧有一个按钮单击时以特定方式更改状态.这种分离在大型复杂应用程序中具有许多优势.

You seperate "indicate something happened" (action) from "do this if X happened" (reducer/middleware). If you call reducer directly then you don't have this separation so if you refactor a button that dispatched INCREMENT to a button that executes one specific reducer you just changed the code to having a button that when clicked indicates INCREMENT happened to having a button that when clicked changes the state in a particular way. There are many advantages that this separation can have in big complex applications.

Facebook 有一个大型应用程序,世界上多个地方的多人都在其中工作(Facebook 聊天),在这个应用程序中,有多个组件应该表明发生了某些事情,但会直接改变状态或导致破坏其他人的副作用人们的代码.所以他们想出了一个模式来解决这个问题.开发人员现在可以创建仅指示发生的事情的组件,以便其他开发人员可以编写代码,当某些事情发生时需要做什么.

Facebook had a large app where multiple people in multiple locations in the world worked on (facebook chat) and in this app there are multiple components that should indicate something happened but would instead directly change the state or caused side effects that broke other people's code. So they came up with a pattern that fixed this. Developers could now create components that would only indicate that something happened so other developers could write the code what needs to done when certain things happen.

redux devtools 保存操作和结果状态,因此可以更轻松地进行调试.如果某些事情不起作用,您应该做的第一件事是检查 devtools 以查看是否发送了正确的操作以及它们是否正确更改了状态.

The redux devtools save the actions and the resulting state so debugging can be made easier. If something doesn't work the first thing you should do is check the devtools to see if the correct actions are dispatched and they changed the state correctly.

用actions和reducers写状态只是其中的一部分,你应该使用selectors来读取状态以可组合和可重用的方式.

Writing to state with actions and reducers is just one part, you should use selectors to read state in a composable and re usable way.

这篇关于Redux:为什么我们需要动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆