bindActionCreators(actionCreators, dispatch) มันคืออะไร ใน Redux

เรื่องมันมีอยู่ว่าผมกำลังที่จะ bind action creator ใน component ที่กำลังทำงานอยู่ ก็มีความสงสัยว่า เราต้องทำแบบนี้ตลอดเลยหรอ

const mapDispatchToProps = (dispatch, ownProps) => {
return {
dispatch1: () => {
dispatch(actionCreator)
}
}
}

ก็เลยไปเจอ http://redux.js.org/docs/api/bindActionCreators.html และ https://stackoverflow.com/questions/41342540/what-is-difference-between-dispatch-and-bindactioncreators

คำอธิบายคร่าวๆ เบื้องต้นบอกว่า การใช้ bindActionCreators แบบนี้

const mapDispatchToProps = (dispatch, ownProps) => {
return bindActionCreators({
getBooks: getBooks
}, dispatch);
}

ให้ผลลัพธ์เหมือนกันกับการ dispatch เอง

const mapDispatchToProps = (dispatch, ownProps) => {
return {
getBooks: () => {
dispatch(getBooks)
}
}
}

และประโยชน์ของมันจริงๆ คือ สิ่งนี้

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.

ซึ่งผมเองก็ยังไม่เข้าใจ ยังไม่เห็นภาพเท่าไหร่นัก หากเพื่อนๆคนไหนมีประสบการณ์ ช่วยแชร์กันด้วยนะครับผม

LINE Engineer x Software Craftsmanship

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade