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

相关推荐
一只小风华~9 分钟前
学习笔记:Vue Router 中的链接匹配机制与样式控制
前端·javascript·vue.js·笔记·学习·ecmascript
Jerry_Rod19 分钟前
react+umijs 项目快速学习
前端·react.js
京东云开发者25 分钟前
浅析cef在win和mac上的适配
前端
uhakadotcom32 分钟前
在chrome浏览器插件之中,options.html和options.js常用来做什么事情
前端·javascript·面试
西瓜树枝36 分钟前
Chrome 扩展开发从入门到实践:以 Cookie 跨页提取工具为例,拆解核心模块与交互逻辑
前端·javascript·chrome
gplitems1231 小时前
Download:Blaxcut - Barbershop & Hair Salon WordPress Theme
前端
拜无忧1 小时前
【DEMO】互动信息墙 - 无限流动版-点击放大
前端
冰糖雪梨dd1 小时前
JS中new的过程发生了什么
开发语言·javascript·原型模式
AliPaPa1 小时前
你可能忽略了useSyncExternalStore + useOptimistic + useTransition
前端·react.js