swiftwind0405 / blog

my blog within git issues
9 stars 1 forks source link

【React】React Hooks #51

Open swiftwind0405 opened 4 years ago

swiftwind0405 commented 4 years ago

概念

什么是 React Hooks:

为什么要用 React Hooks:

Hooks 组件的目标并不是取代 class component 组件,而是增加函数式组件的使用率,明确通用工具函数与业务工具函数的边界,鼓励开发者将业务通用的逻辑封装成 React Hooks 而不是工具函数。

钩子

钩子 用法 作用
useState const [state, changeState] = useState(initialValue) 用于生成状态以及改变状态的方法
useEffect useEffect(fn, [...relativeState]) 用于生成与状态绑定的副作用
useCallback useCallback(fn, [...relativeState]) 用于生成与状态绑定的回调函数
useMemo useMemo(fn, [...relativeState]) 用于生成与状态绑定的组件/计算结果
useRef const newRef = useRef(initialValue) 用于 获取节点实例 / 数据保存

Hooks 的生命周期

image

自定义 Hooks 案例

useDebounce(防抖)

// 防抖
function debounce(func, ms = 30) {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);

        timeout = setTimeout(() => {
            func.apply(context, args)
        }, ms);
    }
}

// 自定义Hooks
const useDebounce = (fn, ms = 30, deps = []) => {
    let timeout = useRef()
    useEffect(() => {
        if (timeout.current) clearTimeout(timeout.current)
        timeout.current = setTimeout(() => fn(), ms)
    }, deps)

    const cancel = () => {
        clearTimeout(timeout.current)
        timeout = null
    }

    return [cancel]
  }

useThrottle(节流)

// 节流
function throttle(func, ms) {
    let previous = 0;
    return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if (now - previous > ms) {
            func.apply(context, args);
            previous = now;
        }
    }
}

// 自定义Hooks
const useThrottle = (fn, ms = 30, deps = []) => {
    let previous = useRef(0)
    let [time, setTime] = useState(ms)
    useEffect(() => {
        let now = Date.now();
        if (now - previous.current > time) {
            fn();
            previous.current = now;
        }
    }, deps)

    const cancel = () => {
        setTime(0)
    }

    return [cancel]
  }

useUpdate

const useUpdate = () => {
    const [, setFlag] = useState()
    const update = () => {
        setFlag(Date.now())
    }

    return update
}

参考文档