1、connect理解
1.要在constructor-super里接收context对象
2. 给组件(class / pure function)指定contextType属性,用来接收store对象
以下代码模拟了connect(类似react-redux里connect的功能)高阶组件的实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function connect(mapStateToProps=doNothing, mapDispatchToProps=doNothing){ return function( WrappedComponent ){ class HOC extends React.Component{ constructor(props, context){ super(props, context); } render(){ const store = this.context.store; const stateProps = mapStateToProps(store.getState());// deliver state const dispatchProps = mapDispatchToProps(store.dispatch);// deliver dispatch const props = {...stateProps, ...dispatchProps}; return <WrappedComponent {...props}/>; } } HOC.contextTypes = { // get store from context store: PropTypes.object } return HOC; } } export {connect}; |
2、在子组件使用
1 2 3 4 5 6 7 8 9 |
const mapStateToProps = state => ({ demo: state.demo }) const mapDispatchToProps = dispatch => ({ handleNumber: action => dispatch(action) }) export default connect(mapStateToProps, mapDispatchToProps)(App) |
原文地址:https://www.cnblogs.com/surfer/p/11378963.html