react-redux的connect函数实现

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

storeContext.js

import { createContext } from "react";

export const StoreContext = createContext()

connect.js

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 
      }
    }
    NewComponent.contextType = StoreContext
    return NewComponent
  }
} 

index.js 

export {connect} from './connect'
export { StoreContext } from './storeContext'

在入口文件index.js引入

import store from "./store"
import { StoreContext } from "./使用redux/hoc"


const root = ReactDOM.createRoot(document.querySelector("#root"))
root.render(
  
    
      
    
  
  )

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

你可能感兴趣的:(React学习记录,react.js,javascript,前端)