组件,容器和mapDispatchToProps之间的Redux关系,mapDispatchToProps

时间:2016-08-24 07:17:33

标签: reactjs react-redux

我看了Presentational and Container ComponentsSmart and Dumb Components in React

概念:

components for “dumb” React components ;  
containers for “smart” React components ;  

但他们没有提到mapDispatchToPropsmapDispatchToProps

是否意味着我应该从容器中获取stateaction,并且不要在组件中使用mapDispatchToPropsmapDispatchToProps ??? 或者意味着我可以使用mapDispatchToProps但不要在组件中使用mapDispatchToProps ???

我对这个组件,容器概念感到困惑

2 个答案:

答案 0 :(得分:3)

演示组件定义了事物的外观和不应该连接到商店的方式。这是一个演示/哑巴组件的例子:

import React from "react"
import styles from "./styles.css"

const TodoList = ({ todos, removeTodo }) => (
  <div className={ styles.todoList }>
    { ... }
  </div>
)

export default TodoList

容器定义了工作方式,不应将DOM标记或样式放在这种组件中。它连接到商店,只向Presentationational / Dumb组件提供数据。以下是Container / Smart组件的示例:

import { connect } from "react-redux"
import { removeTodo } from "actions/todos"
import TodoList from "components/TodoList"

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

const mapDispatchToProps = (dispatch) => ({
  removeTodo(todoId) {
    dispatch(removeTodo(todoId))
  },
})

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

export default TodoListContainer

因此,要回答您的问题,您不应在演示文稿/ Dumb组件中使用mapStateToPropsmapDispatchToProps

答案 1 :(得分:0)