Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

reactjs - When would bindActionCreators be used in react/redux?

Redux docs for bindActionCreators states that:

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.

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

Which kind of component would not be aware of 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)
}

vs

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

function mapDispatchToProps(dispatch) {
  return {
    someCallback: (postId, index) => {
      dispatch({
        type: 'REMOVE_COMMENT',
        postId,
        index
      })
    }
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...