通过 connect 和 mapDispatchToProps 反应 redux 传递事件处理程序与使用 props 渲染 child

React redux passing event handler through connect & mapDispatchToProps vs. rendering child with props

通过 react-redux 文档,我试图理解为什么 todo example uses connect and mapDispatchToProps vs why the reddit example 使用更传统的渲染方法并通过处理程序将调度作为 props 传递给 child 组件。是否有一个原因?我只能猜测这是因为前一个例子有一个容器组件只对应 一个 个展示组件,而后一个例子的容器组件包含 两个 个展示组件所以在两个组件上使用连接(也不可能)是没有意义的。

todo example :

const getVisibleTodos = (todos, filter) => {
...

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

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

reddit example:

class App extends Component {
...
  handleChange(nextReddit) {
    this.props.dispatch(selectReddit(nextReddit))
  }
...

render() {
    ...
    return (
      <div>
        <Picker value={selectedReddit}
                onChange={this.handleChange}
                options={[ 'reactjs', 'frontend' ]} />
        <p>
...

dispatch 传递给您的组件是完全可以的,除非您不希望您的组件滥用 dispatch 函数并调度不应从该组件调度的操作!

如果你想限制你的组件,你不想将 dispatch 直接传递给组件。您需要通过 mapDispatchToProps.

传递特定的动作创建者

我认为这真的归结为编码标准。如果你决定对你的组件严格并且不允许它们直接派发任何动作,你可以使用 mapDispatchToProps 只传递特定的动作创建者。

奖励: 在第一个示例中,您将 (id) => dispatch(toggleTodo(id)) 函数传递给您的组件。尝试使用 redux 中的 bindActionCreators 而不是手动创建该函数!祝你好运。

更新

export const dataLoadRequest = () => {
  return {
    type: 'DATA_LOAD_REQUEST',
  }
}

在你的 Component.js 文件中,你需要导入两个东西。

import { dataLoadRequest } from 'actions.js';
import { bindActionCreators } from 'redux';

class Component extends React.Component{
  ...
  componentDidMount(){
    this.props.actions.dataLoadRequest();
  }
  ...
}

const mapStateToProps = (state) => ({
  ...
});

const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(dataLoadRequest, dispatch)
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Component);