加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 什么时候bindActionCreators会用在react/redux中?

发布时间:2020-12-15 20:55:16 所属栏目:百科 来源:网络整理
导读:看一下 bindActionCreators的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的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的例子?什么样的组件不会意识到Redux?

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

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

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

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

VS

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

function mapDispatchToProps(dispatch) {
  return {
    someCallback: (postId,index) => {
      dispatch({
        type: 'REMOVE_COMMENT',postId,index
      })
    }
  }
}
在99%的情况下,它与React-Redux connect()函数一起使用,作为mapDispatchToProps参数的一部分.它可以在您提供的mapDispatch函数中显式使用,或者如果您使用对象速记语法并将一个充满动作创建者的对象传递给连接,则会自动使用它.

我们的想法是,通过预绑定动作创建者,您传递给connect()的组件在技术上“不知道”它已连接 – 它只知道它需要运行this.props.someCallback().另一方面,如果你没有绑定动作创建者,并调用this.props.dispatch(someActionCreator()),现在组件“知道”它已连接,因为它期望props.dispatch存在.

我在Idiomatic Redux: Why use action creators?的博客中写了一些关于这个主题的想法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读