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

相关推荐
web守墓人38 分钟前
【前端】ikun-markdown: 纯js实现markdown到富文本html的转换库
前端·javascript·html
Savior`L44 分钟前
CSS知识复习5
前端·css
许白掰44 分钟前
Linux入门篇学习——Linux 工具之 make 工具和 makefile 文件
linux·运维·服务器·前端·学习·编辑器
中微子5 小时前
🔥 React Context 面试必考!从源码到实战的完整攻略 | 99%的人都不知道的性能陷阱
前端·react.js
秋田君6 小时前
深入理解JavaScript设计模式之命令模式
javascript·设计模式·命令模式
中微子6 小时前
React 状态管理 源码深度解析
前端·react.js
风吹落叶花飘荡7 小时前
2025 Next.js项目提前编译并在服务器
服务器·开发语言·javascript
加减法原则7 小时前
Vue3 组合式函数:让你的代码复用如丝般顺滑
前端·vue.js
yanlele8 小时前
我用爬虫抓取了 25 年 6 月掘金热门面试文章
前端·javascript·面试
lichenyang4538 小时前
React移动端开发项目优化
前端·react.js·前端框架