• react-hooks的节流与闭包,以及useCallback的用处


    1. import { useEffect, useCallback, useRef } from 'react';
    2. function useThrottle(fn: Function, delay: any, dep = []) {
    3. //用useRef --确保 useCallback里面的值是最新的,如果用useState会形成闭包,导致return不了最新的函数
    4. const { current } = useRef<any>({ fn, timer:null })
    5. useEffect(function () {
    6. current.fn = fn;
    7. }, [fn]);
    8. return useCallback(function f(this: any) {
    9. if (!current.timer) {
    10. current.timer = setTimeout(() => {
    11. delete current.timer
    12. }, delay)
    13. current.fn.call(this, arguments)
    14. }
    15. }, dep)
    16. }
    17. export default useThrottle;

    使用:

    1. /** 点击事件 */
    2. function handleClickJitter(type = '') {
    3. if(type == 'debounce') {
    4. setText("已处理")
    5. }else {
    6. console.log("执行一次");
    7. setThrottleText(`${new Date().getSeconds()}`)
    8. }
    9. }
    10. return (
    11. <Fragment>
    12. <button onClick={useThrottle(() =>{handleClickJitter('throttle')},3000)} />
    13. <div className={textThrottleCls}>{throttleText}div>
    14. div>
    15. Fragment>
    16. );

    •  useCallback的作用(性能优化)

    useCalback就是对函数起一个“缓存”作用,当该函数被父组件作为props传递给字组件子组件时,让props“无变化”,因此达到不会让子组件重复渲染的目的。

    函数式子组件需要搭配 React.memo使用!!!

    无论子组件是pureComponent还是用React.memo进行包裹,都会让子组件render,而配合useCallback使用就能让子组件不随父组件render。

    1. const BtnMemo = React.memo((props: any) => {
    2. const { click } = props
    3. console.log("渲染一次");
    4. return (
    5. <button className="down" onClick={click}>节流button>
    6. )
    7. })
    8. const throttleJitterCon = (props: IThrottleJitterConProps) => {
    9. const [throttleText, setThrottleText] = useState("初始")
    10. /** 点击事件 */
    11. function handleClickJitter(type = '') {
    12. if(type == 'debounce') {
    13. setText("已处理")
    14. }else {
    15. console.log("执行一次");
    16. setThrottleText(`${new Date().getSeconds()}`)
    17. }
    18. }
    19. return (
    20. <Fragment>
    21. <button click={useThrottle(() =>{handleClickJitter('throttle')},3000)} />
    22. <div className={textThrottleCls}>{throttleText}div>
    23. div>
    24. Fragment>
    25. );

     看反例,去掉useCallback的情况:

    1. function useThrottle(fn: Function, delay: any, dep = []) {
    2. //用useRef --确保 useCallback里面的值是最新的,如果用useState会形成闭包,导致return不了最新的函数
    3. const { current } = useRef<any>({ fn, timer:null })
    4. useEffect(function () {
    5. current.fn = fn;
    6. }, [fn]);
    7. return function f(this: any) {
    8. if (!current.timer) {
    9. current.timer = setTimeout(() => {
    10. delete current.timer
    11. }, delay)
    12. current.fn.call(this, arguments)
    13. }
    14. }
    15. }

    可以看到,执行一次后,btnMemo就会跟着渲染一次。(造成了不必要的渲染,复杂业务逻辑下下,会对项目有影响)

     不用Hook封装节流方法的情况,看是怎么形成闭包的:

    1. const BtnMemo = React.memo((props: any) => {
    2. const { click } = props
    3. return (
    4. <button className="down" onClick={click}>节流button>
    5. )
    6. })
    7. const throttleJitterCon = (props: IThrottleJitterConProps) => {
    8. const [throttleText, setThrottleText] = useState("初始")
    9. /** 节流:在一定时间内只能执行一次 */
    10. const throttleFunc = (fn: Function, delay:any) => {
    11. let timer: any
    12. return useCallback(function(this:any) {
    13. console.log("throttleText--useCallback",throttleText);
    14. if (!timer) {
    15. timer = setTimeout(() => {
    16. timer = null
    17. }, delay)
    18. fn.apply(this, arguments)
    19. }
    20. },[])
    21. }
    22. console.log("throttleText++++++++++++",throttleText);
    23. /** 点击事件 */
    24. function handleClickJitter(type = '') {
    25. if(type == 'debounce') {
    26. setText("已处理")
    27. }else {
    28. setThrottleText(`${new Date().getSeconds()}`)
    29. }
    30. }
    31. return (
    32. <Fragment>
    33. <div className="btnGroup">
    34. <BtnMemo click={throttleFunc(() =>{handleClickJitter('throttle')},3000)} />
    35. <div className={textThrottleCls}>{throttleText}div>
    36. div>
    37. Fragment>
    38. );
    39. }
    40. export default throttleJitterCon;

    throttleFunc函数里是可以访问外部作用域的 throttleText变量。也验证了闭包的含义:

    • 红宝书:闭包是指有权访问另一个函数作用域中变量的函数
    • MDN: 闭包是指那些能够访问自由变量的函数,这里的自由变量是指外部作用域中的变量

    我的源代码: https://github.com/BBbila/my-mixed-bag/tree/main/src/ReatHooks/throttleJitter

  • 相关阅读:
    Blazor 发布WebAssembly使用Brotli 压缩提升初次加载速度
    JavaScript 笔记| 青训营笔记
    HTML+CSS+JS环境保护网页设计期末课程大作业 web前端开发技术 web课程设计 网页规划与设计
    深度学习入门:使用CMSIS-NN在微控制器上部署模型的完整指南与Python Jupyter实践
    ssm广西壮族文化宣传网站的设计与实现毕业设计-附源码230932
    手机无线投屏到windows11电脑
    Python学生成绩管信息理系统(面向对象)(成绩管理篇)
    啥?PS一秒成图?Adobe的逆天黑科技大公开
    42. 【Android教程】活动:Activity
    Vue基础面试题11-19
  • 原文地址:https://blog.csdn.net/qq_40610760/article/details/127869228