react-redux 如何在子組件里訪問store對象


1. 要在constructor-super里接收context對象

2. 給組件(class / pure function)指定contextType屬性,用來接收store對象

以下代碼模擬了connect(類似react-redux里connect的功能)高階組件的實現:

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};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM