mapDispatchToProps: any point?

2020-06-01 02:39发布

问题:

I was wondering if there was still a point using mapDispatchToProps today. I'm working on the redux documentation tutorials (to build a todo list) where VisibleTodoList is described as:

import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'

const getVisibleTodos = (todos, filter) => {
  switch (filter) {
    case 'SHOW_ALL':
      return todos
    case 'SHOW_COMPLETED':
      return todos.filter(t => t.completed)
    case 'SHOW_ACTIVE':
      return todos.filter(t => !t.completed)
  }
}

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}

const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList)

export default VisibleTodoList

However, I've been told that today, I could simply not to define mapDispatchToProps and connect everything through:

const VisibleTodoList = connect(
  mapStateToProps,
  toggleTodo
)(TodoList)

Is it right? And if so, what is the point to write a mapDispatchToProps? Is there any drawbacks to simply returning the action?

Thanks!

回答1:

To clarify the other Mark's comment:

The second argument to connect() can take two main forms. If you pass a function as the argument, connect() assumes you want to handle dispatch preparation yourself, calls your function with dispatch as an argument, and merges the result into the props for your component.

If you pass in an object as the second argument to connect(), it assumes you've given it a map of prop names to action creators, and so it automatically runs all of them through the bindActionCreators utility and uses the result as props.

However, passing a single action creator as the second argument, as your example appears to do, would not do what you want, as connect() would interpret that as a preparation function and not an action creator that needs to be bound.

So yes, connect() supports a shorthand syntax of passing in an object full of action creators as the second argument, but there are still good use cases for passing in an actual mapDispatchToProps function to do things yourself (especially if your dispatch prep relies on the actual prop values in some way).

You might want to refer to the API docs for `connect().



回答2:

connect() will automatically bind dispatch to your actions if they are passed in as an object of function names.

So no, you don't need to implement mapStateToProps. Instead you can just pass you actions like this:

export default connect((state) => state, {
  action1,
  action2,
})(MyComponent);