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 <WrapperComponent {...this.props} {...mapStateToProps(this.context.getState())} {...mapDispatchToProps(this.context.dispatch)} />}}NewComponent.contextType = StoreContextreturn 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(<Provider store={store}><StoreContext.Provider value={store}><App/></StoreContext.Provider></Provider>)
通过context来解耦connect文件中对store的依赖,使connect的独立封装性更好。