React 灵感模式 create = (灵感起源) => (感应) => {灵感硕果}

584 阅读1分钟
灵感模式1
const create = (fn) => (props, ref) => {
    const [, forceUpdate] = useReducer((c) => c + 1, 0);
    const [ins] = useState(() => fn(forceUpdate));
    return ins(props, ref);
}
const Counter = create((render) => {
    let count = 1;
    const onClick = () => {
        count += 1;
        render();
    }
    return (props) => {
        return <div onClick={onClick}>{count}</div>
    }
})
灵感模式2
export const create = (fn:any) => (Com: any) => (props:any) => useObserver(() => Com(props), fn);


function useObserver(fn:any, init:any) {
    const [,forceUpdate] = useReducer((c) => c + 1, 0);
    const mounted = useRef(false);
    if (!mounted.current) {
        mounted.current = true;
        init(forceUpdate);
    }
    return fn();
}
灵感模式3
const createModel = (model) => () => {
    const localModal = useRef({});
    const [,setState] = useState(() => {
        const get = () => localModal.current;
        const set = (payload) => {
            if (typeof payload === 'function') {
                payload = payload(localModal.current);
            }
            Object.assign(localModal.current, payload);
            setState(c => !c);
        }
        localModal.current = model({ get, set});
        return false;
    })
    return localModal.current;
}
const counter = ({get, set}) => ({
    count: 1,
    add: () => {
        const { count } = get();
        set({ count: count + 1 })
    }
})

const useCounter = createModel(counter);


const Counter = () => {
    const { count, add } = useCounter();
    return <div onClick={add}>{count}</div>
}