Open swiftwind0405 opened 4 years ago
什么是 React Hooks:
为什么要用 React Hooks:
Hooks 组件的目标并不是取代 class component 组件,而是增加函数式组件的使用率,明确通用工具函数与业务工具函数的边界,鼓励开发者将业务通用的逻辑封装成 React Hooks 而不是工具函数。
// 防抖 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] }
// 节流 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] }
const useUpdate = () => { const [, setFlag] = useState() const update = () => { setFlag(Date.now()) } return update }
概念
什么是 React Hooks:
为什么要用 React Hooks:
Hooks 组件的目标并不是取代 class component 组件,而是增加函数式组件的使用率,明确通用工具函数与业务工具函数的边界,鼓励开发者将业务通用的逻辑封装成 React Hooks 而不是工具函数。
钩子
Hooks 的生命周期
自定义 Hooks 案例
useDebounce(防抖)
useThrottle(节流)
useUpdate
参考文档