极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (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