美文网首页
react hooks相关

react hooks相关

作者: sweetBoy_9126 | 来源:发表于2020-03-27 15:55 被阅读0次

1.有些时候我们监听数据变化的时候不希望拿到第一次初始化的数据,这时候我们就需要额外加一个计数器,当它大于1的时候才去监听

const useUpdate = (dep: boolean, fn: () => void) => {
  const [count, setCount] = useState(0)
  useEffect(() => {
    setCount(x => x + 1)
  }, [dep])
  useEffect(() => {
    if (count > 1) {
      fn()
    }
  }, [count])
}

使用useRef来优化

const useUpdate = (dep: boolean, fn: () => void) => {
  const isFirst = useRef(true)
  useEffect(() => {
    if (isFirst.current) {
      isFirst.current = false;
      return
    }
    fn()
  }, [dep])
}

上面的dep就是我们依赖的数据,fn就是我们数据变化后需要作出的修改

相关文章

  • 十个案例学会 React Hooks

    在学会使用React Hooks之前,可以先看一下相关原理学习React Hooks 前言 在 React 的世界...

  • react hooks相关

    1.有些时候我们监听数据变化的时候不希望拿到第一次初始化的数据,这时候我们就需要额外加一个计数器,当它大于1的时候...

  • React Hooks

    React Hooks Hooks其实就是有状态的函数式组件。 React Hooks让React的成本降低了很多...

  • react 整体疑问

    组件该如何拆分react 相关 什么时候选择react-hooks react生命周期 哪些will被替换 g...

  • react-hooks

    前置 学习面试视频 总结react hooks react-hooks react-hooks为函数组件提供了一些...

  • React Hooks

    前言 React Conf 2018 上 React 提出了关于 React Hooks 的提案,Hooks 作为...

  • 5分钟简单了解React-Hooks

    首先附上官网正文?:React Hooks Hooks are a new addition in React 1...

  • react-hooks

    react-hooks react-hooks 是react16.8以后,react新增的钩子API,目的是增加代...

  • React-hooks API介绍

    react-hooks HOOKS hooks概念在React Conf 2018被提出来,并将在未来的版本中被...

  • React Hooks 入门

    React Hooks 是 React v16.8 版本引入了全新的 API。 React Hooks 基本概念 ...

网友评论

      本文标题:react hooks相关

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