bindActionCreators 的 Redux 文档指出:
bindActionCreators
的唯一用例是当您想要将一些动作创建者传递给不了解 Redux 的组件,并且您不想将调度或 Redux 存储传递给它时。
将使用/需要 bindActionCreators
的示例是什么?
哪种组件不会意识到 Redux ?
两种选择的优点/缺点是什么?
//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
})
}
}
}
原文由 d.code 发布,翻译遵循 CC BY-SA 4.0 许可协议
我不认为最受欢迎的答案实际上解决了这个问题。
下面的所有示例基本上都做同样的事情,并遵循没有“预绑定”的概念。
Option
#3
is just a shorthand for option#1
, so the real question why one would use option#1
vs option#2
.我已经看到它们都在 react-redux 代码库中使用,我发现它相当混乱。我认为混乱来自这样一个事实,即
react-redux
doc 中的所有 示例 都使用bindActionCreators
而 bindActionCreators 的文档(如问题本身所引用的)说不要将它与 react 一起使用-redux。我想答案是代码库的一致性,但我个人更喜欢在需要时将操作显式包装在 调度 中。