Skip to content
On this page

react-redux源码

jsx
import { createContext, useContext, useMemo, useState, useLayoutEffect } from 'react';
import { bindActionCreators } from 'redux';

// 创建上下文对象
const ThemeContext = createContext();

// Provider
export function Provider(props) {
    return (
        <ThemeContext.Provider
            value={{
                store: props.store
            }}>
            {props.children}
        </ThemeContext.Provider>
    )
};

// connect
export function connect(mapStateToProps, mapDispatchToProps) {
    if (!mapStateToProps) {
        mapStateToProps = function mapStateToProps() {
            return {};
        };
    }
    if (!mapDispatchToProps) {
        mapDispatchToProps = function mapDispatchToProps() {
            return {};
        };
    }
    return function HOC(Component) {
        return function Proxy(props) {
            let { store } = useContext(ThemeContext),
                { getState, dispatch, subscribe } = store;

            // 处理状态
            let state = getState();
            state = useMemo(() => mapStateToProps(state), [state]);

            // 处理任务派发
            let dispatchToProps = useMemo(() => {
                if (typeof mapDispatchToProps === 'function') {
                    return mapDispatchToProps(dispatch);
                }
                return bindActionCreators(mapDispatchToProps, dispatch);
            }, [dispatch]);

            // 向事件池注入方法
            const [, forceUpdate] = useState(0);
            useLayoutEffect(() => {
                return subscribe(() => forceUpdate(+new Date()));
            }, [subscribe]);

            return <Component 
                {...props} 
                {...state} 
                {...dispatchToProps} 
            />
        }
    }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
沪ICP备20006251号-1