什么时候在 react/redux 中使用 bindActionCreators? [英] When would bindActionCreators be used in react/redux?

查看:25
本文介绍了什么时候在 react/redux 中使用 bindActionCreators?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Redux 文档指出:

bindActionCreators 的唯一用例是当您想将一些动作创建者传递给不知道 Redux 的组件,并且您不想传递 dispatch 或 Redux 存储时到它.

The only use case for bindActionCreators is when you want to pass some action creators down to a component that isn't aware of Redux, and you don't want to pass dispatch or the Redux store to it.

使用/需要 bindActionCreators 的示例是什么?

What would be an example where bindActionCreators would be used/needed?

哪种组件不知道Redux?

这两种选择的优缺点是什么?

What are the advantages/disadvantages of both options?

//actionCreator
import * as actionCreators from './actionCreators'

function mapStateToProps(state) {
  return {
    posts: state.posts,
    comments: state.comments
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch)
}

对比

function mapStateToProps(state) {
  return {
    posts: state.posts,
    comments: state.comments
  }
}

function mapDispatchToProps(dispatch) {
  return {
    someCallback: (postId, index) => {
      dispatch({
        type: 'REMOVE_COMMENT',
        postId,
        index
      })
    }
  }
}

推荐答案

我不认为最受欢迎的答案实际上解决了问题.

I don't think that the most popular answer, actually addresses the question.

下面的所有示例基本上都做同样的事情,并遵循无预绑定"的概念.

All of the examples below essentially do the same thing and follow the no "pre-binding" concept.

// option 1
const mapDispatchToProps = (dispatch) => ({
  action: () => dispatch(action())
})


// option 2
const mapDispatchToProps = (dispatch) => ({
  action: bindActionCreators(action, dispatch)
})


// option 3
const mapDispatchToProps = {
  action: action
}

Option #3 只是 option #1 的简写,所以真正的问题是为什么要使用 option #1 vs option <代码>#2.我已经看到它们都用于 react-redux 代码库,我发现它相当混乱.

Option #3 is just a shorthand for option #1 , so the real question why one would use option #1 vs option #2. I've seen both of them used in react-redux codebase, and I find it is rather confusing.

我认为混淆来自于所有 examples 使用 bindActionCreatorsbindActionCreators(如问题本身所引用)说不要将它与 react-redux 一起使用.

I think the confusion comes from the fact that all of the examples in react-redux doc uses bindActionCreators while the doc for bindActionCreators (as quoted in the question itself) says to not use it with react-redux.

我想答案是代码库的一致性,但我个人更喜欢在需要时在 dispatch 中显式包装操作.

I guess the answer is consistency in the codebase, but I personally prefer explicitly wrapping actions in dispatch whenever needed.

这篇关于什么时候在 react/redux 中使用 bindActionCreators?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆