鍍金池/ 問(wèn)答/HTML/ redux 子組件如何獲取 bindActionCreators方法綁定的 ac

redux 子組件如何獲取 bindActionCreators方法綁定的 action?

//import省略

const store = applyMiddleware(ReduxThunk)(createStore)(reducers);

const App = connect(
    state => (state),
    dispatch => ({
        action: bindActionCreators(actions, dispatch)
    })
)(Component);

const mountPoint = document.createElement('div');
mountPoint.setAttribute('id', 'root');
document.body.appendChild(mountPoint);

render(
    <Provider store={store}>
        <App />
    </Provider>,
    mountPoint
);

我知道子組件可以通過(guò)設(shè)置contextTypes來(lái)獲取store,但是store里面只有dispatch、getState等方法,并沒(méi)有bindActionCreators處理過(guò)的action。
這導(dǎo)致我在子組件中,又要重新用dispatch去發(fā)起更新state請(qǐng)求

我猜測(cè)原因時(shí) action 在 App 組件上而不在 Provider 上。
所以子組件想要通過(guò)context獲取action必須在App組件里設(shè)置childContextTypes嗎?

我聽(tīng)說(shuō)redux對(duì)react的context有封裝,如果自己在App組件中寫(xiě)childContextTypes,是不是脫離了redux了?

回答
編輯回答
卟乖

在 react 中應(yīng)用 redux 應(yīng)該遵守容器組件、UI 組件的分層設(shè)計(jì)模式(react-redux)。
如果你在子組件里面有調(diào)用 action 的需求,那么一種是父組件通過(guò) props 傳遞 action 到子組件,還有一種就是創(chuàng)建一個(gè)子組件的容器組件,在容器組件中通過(guò) mapDispatchToProps 來(lái)綁定 actions。
遵循這種設(shè)計(jì)模式讓分層更加清晰、降低耦合,有利于重用和單元測(cè)試。
好的分層設(shè)計(jì)有利于測(cè)試,請(qǐng)看這篇:https://segmentfault.com/a/1190000015935519

2017年10月28日 23:33
編輯回答
孤星
this.props.action.<actionName>
2018年1月24日 08:40