bindActionCreators(actionCreators, dispatch) มันคืออะไร ใน Redux
Jul 30, 2017 · 1 min read
เรื่องมันมีอยู่ว่าผมกำลังที่จะ 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
bindActionCreatorsis when you want to pass some action creators down to a component that isn't aware of Redux, and you don't want to passdispatchor the Redux store to it.
ซึ่งผมเองก็ยังไม่เข้าใจ ยังไม่เห็นภาพเท่าไหร่นัก หากเพื่อนๆคนไหนมีประสบการณ์ ช่วยแชร์กันด้วยนะครับผม
