简体   繁体   English

状态包含在React Redux动作中,而包含在reducer中

[英]State is contained in react redux actions vs. contained in reducers

I'm learning react-redux form the todo example in the docs and don't see why the id of the nextTodo is held in the actions rather than the reducer . 我正在从文档中的todo示例中学习react-redux,看不到为什么nextTodo的id保留在actions而不是reducer Shouldn't this be considered state because it changes overtime as more todos are added? 这不应该被视为状态,因为随着添加的待办事项的增加,它会随着时间变化吗? To me, the purpose of an action is to grab some input from the user and transform it to an action, not generate state. 对我而言,动作的目的是从用户那里获取一些输入并将其转换为动作,而不是生成状态。 It is the reducer's job to create state and change it according to the actions given to it. 还原器的工作是创建状态并根据提供给它的操作更改状态。

Action Code 动作码

let nextTodoId = 0

export const addTodo = (text) => {
  return {
    type: 'ADD_TODO',
    id: nextTodoId++,
    text
  }
}

Reducer code 减速器代码

const todo = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        id: action.id,
        text: action.text,
        completed: false
      }
...
}

That's because the reducer is expected to be a pure function. 这是因为减速器应该是纯函数。 That is, if you run it multiple times with the same parameters, it would return the same result, and the state of the rest of the application would not change. 也就是说,如果使用相同的参数多次运行它,它将返回相同的结果,并且应用程序其余部分的状态不会改变。

For that reason, the reducer can't determine the ID, as if it did, it would cause repeated runs to have different results (ie different return values). 因此,减速器无法确定ID,就好像它确定了ID一样,它将导致重复运行具有不同的结果(即不同的返回值)。

The reducer's job isn't to create state. 减速器的工作不是创建状态。 It's job is to get the existing state and a delta (ie an action) and return a new state. 它的工作是获取现有状态和增量(即动作)并返回新状态。 And it should do so reliably. 而且它应该可靠地这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM