在Redux中使用动作创建者的主要好处是什么?

问题描述

假设我有一个$preg_match_all($pattern,$str,$output,PREG_PATTERN_ORDER); print_r($output[0]); 组件,它将通过其input处理程序来更新状态。

onChange

我认为选项#2更具可读性,那么为什么我要使用动作创建者而不是常规的动作派发?

解决方法

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

动作创建者也可以是异步的并且有副作用。

因此,它简化了组件视图中的用法:

// 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} />;
}

请注意,编写动作创建者更像是“旧API”,您应该立即使用redux-toolkit(2020年)。