chenchenyuyu / chenchenyuyu.github.io

记录点点滴滴
http://cychenyu.com/
2 stars 0 forks source link

reselect原理 #98

Open chenchenyuyu opened 5 years ago

chenchenyuyu commented 5 years ago
const createSelector = (selector1, selector2, resultSelector) => {
    let selectorCache1,  // selector1的结果记忆
        selectorCache2,  // selector2的结果记忆
        resultCache;     // resultSelector的结果记忆
    return (state) => {
        const subState1 = selector1(state);
        const subState2 = selector2(state);

        if (selectorCache1 === subState1 && selectorCache2 === subState2) {
            return resultCache;
        }
        selectorCache1 = subState1;
        selectorCache2 = subState2;     
        resultCache = resultSelector(selectorCache1, selectorCache2);
        return resultCache;
    };
}
chenchenyuyu commented 5 years ago
let memoizeState = null
function mapStateToProps(state) {
    const {a, b, c} = state
    if (!memoizeState) { 
       memoizeState =  {
            a,
            b,
            c,
            fab: f(a,b),
            hbc: h(b,c),
            gac: g(a,c),
            uabc: u(a, b, c)
        }
    } else {
        if (!(a === memoizeState.a && b === memoizeState.b) ) {
            // f should invoke
            memoizeState.fab = f(a, b)
        }
        if (!(b === memoizeState.b && c === memoizeState.c) ) {
            // h should invoke
            memoizeState.hbc = h(b, c)
        }
        if (!(a === memoizeState.a && c === memoizeState.c) ) {
            // g should invoke
            memoizeState.gac = g(a, c)
        }
        if (!(a === memoizeState.a && b === memoizeState.b && c === memoizeState.c) ) {
            // u should invoke
            memoizeState.uabc = u(a, b, c)
        }
        memoizeState.a = a
        memoizeState.b = b
        memoizeState.c = c
    }

    return memoizeState
}
chenchenyuyu commented 5 years ago
import { createSelector } from 'reselect'

fSelector = createSelector(
    a => state.a,
    b => state.b,
    (a, b) => f(a, b)
)
hSelector = createSelector(
    b => state.b,
    c => state.c,
    (b, c) => h(b, c)
)
gSelector =  createSelector(
    a => state.a,
    c => state.c,
    (a, c) => g(a, c)
)
uSelector = createSelector(
    a => state.a,
    b => state.b,
    c => state.c,
    (a, b, c) => u(a, b, c)
)

...
function mapStateToProps(state) {
    const { a, b, c } = state
    return {
        a,
        b,
        c,
        fab: fSelector(state),
        hbc: hSelector(state),
        gac: gSelector(state),
        uabc: uSelector(state)
    }
}