javascript - 在 Redux 中使用 Action 创建器的主要好处是什么?

标签 javascript reactjs redux redux-actions

假设我有一个 input 组件,它将通过其 onChange 处理程序更新状态。

function updateInputState(newvalue) {
  return({
    type: "UPDATE_INPUT_STATE",
    payload: newValue
  });
}

function InputComponent(props) {
  
  function onChange(event) {
    const newValue = event.target.value;

    // OPTION #1 - WITHOUT AN ACTION CREATOR. DISPATCH THE ACTION DIRECTLY
    dispatch({
      type: "UPDATE_INPUT_STATE",
      payload: newValue
    });

    // OPTION #2 - WITH AN ACTION CREATOR
    dispatch(updateInputState(newValue));

  }

  return(
    <input value={props.value} onChange={onchange}/>
  );
}

我认为选项 #2 更具可读性,那么为什么我要使用操作创建器而不是常规操作调度?

最佳答案

主要优点是简单和易于维护,尤其是在 async actions 方面。 .

Action creators can also be asynchronous and have side-effects.

因此它简化了组件 View 中的使用:

// Lets say we suddenly want to make updateInputState async action
function InputComponent(props) {
  function onChange(event) {
    const newValue = event.target.value;
    // Edit its action creator implementation
    dispatch(updateInputState(newValue));

    // on the other hand, without action creator, you need to
    // change this code to async everywhere across the app
    dispatch({
      type: "UPDATE_INPUT_STATE",
      payload: newValue,
    });
  }

  return <input value={props.value} onChange={onchange} />;
}

Dave Ceddia在维护方面提出了这一重要观点:“当您在多个位置复制并粘贴一个操作时,更改会变得更加困难。”

Notice that writing action creators is more like "an old API" you should use redux-toolkit now (2020).

关于javascript - 在 Redux 中使用 Action 创建器的主要好处是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63806936/

相关文章:

javascript - React ErrorBoundary - 只是无法让它工作

javascript - 为什么我要使用 Redux Promise 中间件而不是 Redux Promise?

javascript - 为什么不能将 onclick 处理程序设置为 native 函数?

javascript - amcharts4 水平条形图列右侧的工具提示

javascript - 将 HTML 元素插入到 div 元素中?

reactjs - React-pixi 和 Reagent 导致不变违规

javascript - 从 Javascript 调用 Dart

javascript - 如何使用 blueprintjs/table 渲染表格

reactjs - 组件堆栈跟踪中的错误行号 [TS + React]

javascript - TypeError : Cannot read property 'type' of undefined functional components