在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/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
);

我知道子組件可以通過設置contextTypes來獲取store,但是store里面只有dispatch、getState等方法,并沒有bindActionCreators處理過的action。
這導致我在子組件中,又要重新用dispatch去發(fā)起更新state請求

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

我聽說redux對react的context有封裝,如果自己在App組件中寫childContextTypes,是不是脫離了redux了?

回答
編輯回答
卟乖

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

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