[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))
    }
  }
}

 

你可能感兴趣的:([Redux] Extracting Action Creators)