useRef和createRef区别

2021-02-07  本文已影响0人  shanshanfei

useRef和createRef区别

官网的定义如下:
useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
换句人话说 , useRef 在 react hook 中的作用, 正如官网说的, 它像一个变量, 类似于 this , 它就像一个盒子, 你可以存放任何东西. createRef 每次渲染都会返回一个新的引用,而 useRef 每次都会返回相同的引用。

useRef常见的一个使用场景是:
组件初始化时 保存一个初始值,由于其是组件生命周期中始终是同一个引用,所以对于想要执行一次的操作,可以通过useRef控制,比如:

const myCComponent:React.FC = () => {
  const updateRef = React.useRef(false);

  // other operations 后,updateRef.current = true 

  React.useEffect(() => {
    if(!updateRef.current){
      // doSomething
    }
  }, [])
}

good

上一篇 下一篇

猜你喜欢

热点阅读