[Redux] Extracting Action Creators

We will create an anction creator to manage the dispatch actions, to keep code maintainable and self-documenting by extracting action creators from the components.

let nextTodoId = 0;
const ACTION_CREATOR = {
  addTodo: (text) => {
    return {
          type: 'ADD_TODO',
          id: nextTodoId++,
          text
        }
  },
  setVisibilityFilter: (filter) => {
    return {
      type: 'SET_VISIBILITY_FILTER',
      filter
    }
  },
  toggleTodo: (id) => {
    return {
        type: 'TOGGLE_TODO',
        id
      }
  }
}

Then update the dispatch function:

...

let AddTodo = ({ dispatch }) => {
  let input;

  return (
    <div>
      <input ref={node => {
        input = node;
      }} />
      <button onClick={() => {
        dispatch(ACTION_CREATOR.addTodo(input.value))
        input.value = '';
      }}>
        Add Todo
      </button>
    </div>
  );
};
AddTodo = connect()(AddTodo);

...
const mapDispatchToTodoListProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(ACTION_CREATOR.toggleTodo(id));
    }
  };
};

....
const mapDispatchToLinkProps = (
  dispatch,
  ownProps
) => {
  return {
    onClick: () => {
      dispatch(ACTION_CREATOR.setVisibilityFilter(ownProps.filter))
    }
  }
}
原文地址:https://www.cnblogs.com/Answer1215/p/5186822.html