When would bindActionCreators be used in react/redux?

后端 未结 10 1081
温柔的废话
温柔的废话 2020-12-07 11:04

Redux docs for bindActionCreators states that:

The only use case for bindActionCreators is when you want to pass some action cre

10条回答
  •  悲哀的现实
    2020-12-07 11:46

    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 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.

    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.

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

提交回复
热议问题