connect本质就是使用高阶组件来增强组件属性
connect(mapStateToProps,mapDispatchToProps)(cpn)
-
mapDispatchToProps Function 传入一个函数 并且返回一个对象,返回的对象是你想进行监听的store数据
-
mapDispatchToProps Function 传入一个函数 并且返回一个对象,返回的对象是你想使用dispatch更新store里面数据的方法。
-
cpn Function 想进行属性增强的组件
react根目录 index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './components/App'
import store from './store'
import { themeContext } from './hoc'
const root = ReactDOM.createRoot(document.getElementById('root'));
//传递给App组件以及以下组件store
root.render(
<themeContext.Provider value={store}>
<App />
</themeContext.Provider>
</React.StrictMode>
);
index.js
export { xxConnect} from './connect'
export { themeContext} from './contextStore'
contextStore.js
import React from "react";
export const themeContext = React.createContext()
生成一个context的原因是为了获取到store 在connect.js文件里使用
connect.js
import React, { PureComponent } from 'react'
import { themeContext } from './contextStore'
export function xxConnect(mapStateToProps, mapActionToProps) {
return function EnhanceComponent(NewCpn) {
class newComponent extends PureComponent {
//初始化state值
constructor(props, context) {
super(props, context)
this.state = mapStateToProps(context.getState())
}
//当store数据发生改变的时候调用setState设置新state,然后进行新老state进行对比
componentDidMount() {
this.unSubscribe = this.context.subscribe(() => {
this.setState(mapStateToProps(this.context.getState()))
})
}
render() {
const stateObj = mapStateToProps(this.context.getState())
const dispatchObj = mapActionToProps(this.context.dispatch)
return (
<NewCpn {...this.props} {...stateObj} {...dispatchObj} />
)
}
}
//获取上下文传来的store
newComponent.contextType = themeContext
return newComponent
}
}
大致实现思路就是定义一个函数接受mapStateToProps和mapActionToProps2个参数,然后调用,调用结果会返回一个函数函数内部自定义一个组件,然后在组件render函数内部分别调用mapStateToProps和mapActionToProps2方法获取到需要增强的属性然后进行增强。