• 记几个好用的hooks


    React hook

    useState

    useState是最常用的hook了,就不介绍了。
    useState可以通过调用callback获取最新的state。方便解决异步调用时获取的state是创建异步时的state而无法获取到最新state的情况。

    const [state, setState] = useState(initialState);
    
    useState(lastState=>{
          //get newest state.
          //do something to last state, example: use ... to clone an array or object and modify it.
          return newState;
    }
    

    useEffect

    componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的集大成者,融合了三个生命周期,强大强大。
    负责对某些值进行实时监控。如果第二个可选参数为空,表明在第一次渲染时进行。
    如果是需要清除的副作用,一个return一键清除不留遗憾。

    useRef

    useRef实在是太好用了有木有!!!
    useRef类似一个盒子,可以在.current属性里保存任何可变值,不需要类似于useState一样异步存在延迟,屯在最后一次性更新,而是随时随地更新,方便快捷!

        //use useRef to log the audio amplitude of a recording
        const context = new AudioContext();
        const recorder = context.createScriptProcessor(4096, 1, 1);
        recorder.onaudioprocess = function(e) {
          const inputFrame = e.inputBuffer.getChannelData(0);
          const maxvo = Math.max.apply(null, inputFrame);
          if (maxvo > maxVolume.current) 
                maxVolume.current = maxvo;//if use setState, it will log the lastest value bigger than initial value.
        };
    
        navigator.mediaDevices
          .getUserMedia(mediaConstraints)
          .then(stream => {
            const audioInput = context.createMediaStreamSource(stream);
            audioInput.connect(recorder);
            recorder.connect(context.destination);
          })
          .catch(e => {
            console.error(`Recording Error: ${e}`);
          });
    

    useImperativeHandle

    配合ref使用,让父组件也可以时时刻刻获取到子组件的ref。

    function FancyInput(props, ref) {
      const inputRef = useRef();
      useImperativeHandle(ref, () => ({
        focus: () => {
          inputRef.current.focus();
        }
      }));
      return <input ref={inputRef} ... />;
    }
    FancyInput = forwardRef(FancyInput);
    
    //渲染 <FancyInput ref={inputRef} /> 的父组件可以调用 inputRef.current.focus()。
    

    useContent

    父组件传给子组件,可以穿透多层子组件。可以父组件用setState更新,子组件也可以随时获取最新值。

          //父组件
          export const StateContext= React.createContext<{
            state: string[];
            setState: (state: string[]) => void;
          }>(null);
    
              const [state, setState] = useState(null);
              <StateContext.Provider value={{ state, setState}}>
                <SubComponent />
              </StateContext.Provider>
    
          //子组件
          const { state, setState} = useContext(StateContext);
    

    自定义Hook

    useBoolean

    适用于boolean的state。

    export function useBoolean(
      initialState: boolean
    ): [boolean, { setTrue: () => void; setFalse: () => void; toggle: () => void }] {
      const [value, setValue] = useState(initialState);
      const setTrue = () => setValue(true);
      const setFalse = () => setValue(false);
      const toggle = () => setValue(x => !x);
      return [value, { setTrue, setFalse, toggle }];
    }
    
    //使用
    const [isOpen, { setTrue: openPanel, setFalse: dismissPanel, toggle: togglePanel }] = useBoolean(false);
    openPanel();//打开panel
    dismissPanel();//关闭panel
    togglePanel();//打开时关闭,关闭时打开
    

    useResetState

    重置初始状态

    export function useResetState<S>(initialState?: S): [S, Dispatch<SetStateAction<S>>, () => void] {
      const [state, setState] = useState(initialState);
      const resetState = () => setState(initialState);
      return [state, setState, resetState];
    }
    
    //使用
    const [itemToEdit, setItemToEdit, resetItemToEdit] = useResetState(null as TTSProject);
    setItemToEdit(item);
    resetItemToEdit();//重置成初始状态
    
  • 相关阅读:
    购买绝版书的好地方——淘宝
    ASP.NET MVC轻教程 Step By Step 1 ——入门
    ASP.NET MVC轻教程 Step By Step 2 ——View初探
    快速启动WebDev.WebServer的方法
    Surface RT使用手记
    ASP.NET MVC轻教程 Step By Step 3 ——使用ViewBag
    Asp.net MVC分页实例
    图示近四年来国外主流编程语言发展趋势
    ASP.NET MVC轻教程 Step By Step 4——Model、View和Controller
    Asp.net MVC使用KindEditor4
  • 原文地址:https://www.cnblogs.com/xym4869/p/14049852.html
Copyright © 2020-2023  润新知