在 Redux 中,使用 actionCreators 有什么好处?

In Redux, what is the benefit of using actionCreators?

我目前正在学习 Redux 并且遇到了障碍,我的问题是为什么您需要应用程序在没有它们的情况下运行的操作?他们添加了什么?

import { createStore } from 'redux'

// ACTIONS
const addTodo = (text) => {
  type: 'ADD_TODO',
  text
}

const toggleTodo = (id) => {
  type: 'TOGGLE_TODO',
  id
}

// REDUCER
const todos = (state = [], action) => {
  switch(action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        {
          id: state.length,
          text: action.text,
          complete: false
        }
      ]
    default:
      return state
  }
}

// STORE
const store = createStore(todos)

// TEST
store.dispatch({ type: 'ADD_TODO', text: 'Test' })
console.log(store.getState())

首先,不要混淆 ActionCreatorsActions,它们是不同的东西。

操作只是带有type属性的对象(以及您要添加的任何其他内容) .

ActionCreators 根据提供的逻辑和数据构建动作。 例如,假设一个动作 "updates a contact",那么动作创建者可能被构建为异步流的 thunk,它会将网络请求分派给 API 以更新联系人,一旦它知道 API 调用有效,它会调度操作,可能类似于:

{
  type: "UPDATE_CONTACT",
  data: { prop: "newValue" }
}

使用 CONSTANTS 这对于 maintenance/debugging 大型代码库来说是一种便利。通过使用常量,您的环境将更快地标记拼写错误的 Action,因为常量将不存在。如果您纯粹依赖对象文字或字符串,调试起来可能会更复杂。

为什么要使用动作创建器

ActionCreator 有两个主要用途:

可移植性和可测试性as per the redux docs

我还发现它们对于动态构建最终动作数据很有用。按照我上面的例子,如果你想要 POST 一个联系人,服务器通常会用一个 LOCATION 头响应,给你新的位置( 和可能的 ID)联系方式,您将需要它来进行未来的 GET 或 PUT 请求。使用 actionCreator,我可以将新数据捆绑到最终的操作对象中,然后看起来像:

{
  type: "CREATE_CONTACT",
  data: {
    first_name: "bob",
    last_name: "builder"
    id: 7         // -> provided by API, the actionCreator injected it
  }
}