react-redux的connect函数实现

react-redux对store订阅的实现原理:

storeContext.js

javascript 复制代码
import { createContext } from "react";

export const StoreContext = createContext()

connect.js

javascript 复制代码
import React, { PureComponent } from 'react'
// import store from '../../store';
import {StoreContext} from './storeContext'

export function connect(mapStateToProps, mapDispatchToProps) {
  // 返回高阶组件:函数
  return function(WrapperComponent) {
    // 返回组件
    class NewComponent extends PureComponent {
      constructor(props, context) {
        super(props);
        this.state = mapStateToProps(context.getState())
      }
      // 组件挂载时订阅变化 并更新
      componentDidMount() {
        this.unsubscribe =  this.context.subscribe(() => {
          this.setState(mapStateToProps(this.context.getState()))
        })
      }
      // 组件卸载时  关闭订阅
      componentWillUnmount() {
        this.unsubscribe()
      }

      render() {
        // 返回组件
        return <WrapperComponent 
          {...this.props} 
          {...mapStateToProps(this.context.getState())} 
          {...mapDispatchToProps(this.context.dispatch)} />
      }
    }
    NewComponent.contextType = StoreContext
    return NewComponent
  }
} 

index.js

javascript 复制代码
export {connect} from './connect'
export { StoreContext } from './storeContext'

在入口文件index.js引入

javascript 复制代码
import store from "./store"
import { StoreContext } from "./使用redux/hoc"


const root = ReactDOM.createRoot(document.querySelector("#root"))
root.render(
  <Provider store={store}>
    <StoreContext.Provider value={store}>
      <App/>
    </StoreContext.Provider>
  </Provider>
  )

通过context来解耦connect文件中对store的依赖,使connect的独立封装性更好。

相关推荐
古拉拉明亮之神11 分钟前
Spark处理过程-转换算子
javascript·ajax·spark
Yvonne爱编码33 分钟前
CSS- 4.1 浮动(Float)
前端·css·html·github·html5·hbuilder
timeguys1 小时前
【前端】[vue3] [uni-app]使用 vantUI 框架
前端·uni-app
岁岁岁平安1 小时前
Vue3学习(组合式API——Watch侦听器、watchEffect()详解)
前端·javascript·vue.js·学习·watch侦听器·组合式api
uwvwko2 小时前
BUUCTF——web刷题第一页题解
android·前端·数据库·php·web·ctf
有事没事实验室2 小时前
CSS 浮动与定位以及定位中z-index的堆叠问题
前端·css·开源
Stringzhua2 小时前
JavaScript入门【3】面向对象
javascript
2501_915373882 小时前
Vue路由深度解析:Vue Router与导航守卫
前端·javascript·vue.js
小妖6662 小时前
前端表格滑动滚动条太费事,做个浮动滑动插件
前端
读心悦3 小时前
5000 字总结CSS 中的过渡、动画和变换详解
前端·css·tensorflow