useRef和createRef區(qū)別
官網(wǎng)的定義如下:
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.
換句人話說(shuō) , useRef 在 react hook 中的作用, 正如官網(wǎng)說(shuō)的, 它像一個(gè)變量, 類似于 this , 它就像一個(gè)盒子, 你可以存放任何東西. createRef 每次渲染都會(huì)返回一個(gè)新的引用芋肠,而 useRef 每次都會(huì)返回相同的引用。
useRef常見(jiàn)的一個(gè)使用場(chǎng)景是:
組件初始化時(shí) 保存一個(gè)初始值鸽素,由于其是組件生命周期中始終是同一個(gè)引用薄货,所以對(duì)于想要執(zhí)行一次的操作系草,可以通過(guò)useRef控制闲昭,比如:
const myCComponent:React.FC = () => {
const updateRef = React.useRef(false);
// other operations 后决采,updateRef.current = true
React.useEffect(() => {
if(!updateRef.current){
// doSomething
}
}, [])
}