zoukankan      html  css  js  c++  java
  • 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};
    路漫漫其修远兮,吾将上下而求索。 May stars guide your way⭐⭐⭐
  • 相关阅读:
    BOM和DOM
    js
    前端css
    html介绍
    线程锁&&信号量&&GIL&&线程定时器&&进程池与线程池&&协程
    对于数据库的操作以及配置
    string 迭代器
    递归
    python 操作mysql数据库
    Python编辑器IDLE傻瓜入门
  • 原文地址:https://www.cnblogs.com/surfer/p/11378963.html
Copyright © 2011-2022 走看看