美文网首页
useRef和createRef区别

useRef和createRef区别

作者: shanshanfei | 来源:发表于2021-02-07 14:25 被阅读0次

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

相关文章

网友评论

      本文标题:useRef和createRef区别

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