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

·  阅读 448
React 灵感模式  create = (灵感起源) => (感应) => {灵感硕果}
灵感模式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>
}
复制代码
分类:
前端
标签:
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改