美文网首页
自定义Hook

自定义Hook

作者: Ag_fronted | 来源:发表于2020-12-10 11:08 被阅读0次

    1、usePrevious绑定state先前的值

    import React, { useState, useEffect, useRef } from "react";
    import { Button } from "antd";
    
    function usePrevious(value) {
      1、const ref = useRef();
      useEffect(() => {
        ref.current = value;
      });
      return ref.current;
    
     2、const current = React.useMemo(
        () => ({
          current: 0,
        }),
        []
      );
      React.useEffect(() => {
        current.current = value;
      });
      return current.current;
    }
    
    function Child({ child, handleChild, ...props }) {
      const prevChild = usePrevious(child);
    
      return (
        <div>
          <Button onClick={handleChild}>{`${child} ${prevChild}`}</Button>
        </div>
      );
    }
    
    export default React.memo(Child);
    

    2、useDebounce延迟加载

    import React, { useState } from "react";
    
    const useDebounce = (value, delay) => {
        const [debouncedValue, setDebouncedValue] = React.useState(value);
    
        React.useEffect(() => {
          const handler = setTimeout(() => {
            setDebouncedValue(value);
          }, delay);
    
          return () => {
            clearTimeout(handler);
          };
        }, [value]);
    
        return debouncedValue;
    };
    
    const App = () => {
      const [value, setValue] = React.useState(0);
      const lastValue = useDebounce(value, 500);
    
      return (
        <div>
          <p>
            Current: {value} - Debounced: {lastValue}
          </p>
          <button onClick={() => setValue(value + 1)}>Increment</button>
        </div>
      );
    };
    
    export default App;
    

    相关文章

      网友评论

          本文标题:自定义Hook

          本文链接:https://www.haomeiwen.com/subject/rqvlgktx.html