1

假设我有一个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 更具可读性,那么为什么我要使用动作创建器而不是常规动作调度呢?

4

1 回答 1

3

主要好处是简单性和维护性,尤其是在异步操作方面。

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

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

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

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

于 2020-09-09T07:55:43.270 回答