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的独立封装性更好。

相关推荐
Moonbit8 小时前
招募进行时 | MoonBit AI : 程序语言 & 大模型
前端·后端·面试
excel8 小时前
Vue 3 编译器源码深度解析:transformOn —— v-on 指令的编译过程
前端
excel8 小时前
Vue 编译器核心:transformIf 模块深度解析
前端
CodeToGym8 小时前
Vue2 和 Vue3 生命周期的理解与对比
前端·javascript·vue.js
excel8 小时前
深度解析 Vue 编译器源码:transformFor 的实现原理
前端
excel8 小时前
Vue 编译器源码精读:transformBind —— v-bind 指令的编译核心
前端
excel8 小时前
深入浅出:Vue 编译器中的 transformText —— 如何把模板文本变成高效的渲染代码
前端
excel8 小时前
Vue 编译器源码深析:transformSlotOutlet 的设计与原理
前端
excel8 小时前
Vue 编译器核心源码解读:transformElement.ts
前端
excel8 小时前
Vue 编译器兼容性系统源码详解
前端