极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。

# 在 React Hooks 中实现 usePreviouseValue 取上次渲染的值

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 677 (opens new window)

TODO

Author

回答者: jarbinup (opens new window)

import { useRef } from "react";

type ShouldUpdateFunc<T> = (prev: T | undefined, next: T) => boolean;

const defalutShouldUpdate = <T>(prev?: T, next?: T) => prev !== next;

function usePrevious<T>(
  state: T,
  shouldUpdateFun: ShouldUpdateFunc<T> = defalutShouldUpdate
): T | undefined {
  const prev = useRef<T>();
  const cur = useRef<T>();

  if (shouldUpdateFun(cur.current, state)) {
    prev.current = cur.current;
    cur.current = state;
  }
  return prev.current;
}

export default usePrevious;

ahook 的实现版本 很简洁

Last Updated: 6/26/2022, 10:48:10 AM