mapDispatchToProps:有什么意义吗?

mapDispatchToProps: any point?

我想知道今天使用 mapDispatchToProps 是否还有意义。 我正在处理 redux documentation tutorials(构建待办事项列表),其中 VisibleTodoList 被描述为:

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

但是,今天有人告诉我,我可以简单地不定义 mapDispatchToProps 并通过以下方式连接所有内容:

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

对吗?如果是这样,写一个 mapDispatchToProps 有什么意义?简单地返回操作有什么缺点吗?

谢谢!

connect() 将自动将调度绑定到您的操作,如果它们作为函数名称的对象传入。

所以不,您不需要实现 mapStateToProps。相反,您可以只传递这样的操作:

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

澄清其他马克的评论:

connect() 的第二个参数可以采用两种主要形式。如果你传递一个函数作为参数,connect() 假设你想自己处理调度准备,用 dispatch 作为参数调用你的函数,并将结果合并到你的组件的道具中。

如果您将一个对象作为第二个参数传递给 connect(),它会假定您已将道具名称映射给动作创建者,因此它会自动通过 bindActionCreators 实用程序并将结果用作道具。

但是,将 单个 动作创建者作为第二个参数传递,正如您的示例所做的那样,不会执行您想要的操作,因为 connect() 会解释为作为准备函数而不是需要绑定的动作创建者。

所以是的,connect() 支持 shorthand 语法将充满动作创建者的对象作为第二个参数传递,但仍有很好的用例传递实际的 mapDispatchToProps 函数自己做事(特别是如果你的调度准备以某种方式依赖于实际的 prop 值)。

您可能需要参考 the API docs for `connect()