手写react-redux中connect高阶函数

connect.js文件

import React, { Fragment, PureComponent } from 'react'

import { hocContext } from './createContext'
export function connect(mapStateToProps, mapDispatchToProps) {

    return function (Comp) {
        return class extends PureComponent {
            static contextType = hocContext
            constructor(props, context) {
                super(props)
                this.state = mapStateToProps(context.getState()) //初始化组件中state值
            }
            componentDidMount() {
                this.unSubscribe = this.context.subscribe(() => {
                    //this.forceUpdate() //不能避免无关数据改变时重新渲染
                    this.setState(mapStateToProps(this.context.getState()))
                })
            }
            componentWillUnmount() {
                this.unSubscribe()
            }
            render() {

                return (
                    
                        
                    
                )
            }
        }
    }
}

createContext.js文件

import { createContext } from "react";

export const hocContext = createContext()
export const Provider = hocContext.Provider

index.js文件 

import { Provider } from "./hoc_手写connect/createContext";

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

    
        
    

)

你可能感兴趣的:(react.js,javascript,前端)