前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >useRef与createRef的区别

useRef与createRef的区别

原创
作者头像
挥刀北上
修改2021-02-22 14:42:16
9860
修改2021-02-22 14:42:16
举报
文章被收录于专栏:Node.js开发Node.js开发

createRef 每次渲染都会返回一个新的引用,而 useRef 每次都会返回相同的引用。看代码:

代码语言:javascript
复制
const App = ()=>{
   const [renderIndex,setRenderIndex] = useState(1);
    const refFromUseRef = useRef();
   const refFromCreateRed = createRef();

   
    if (!refFromUseRef.current){
       refFromUseRef.current=renderIndex
   }
    if (!refFromCreateRed.current) {
        refFromCreateRed.current = renderIndex
    }

    return <>
        <p>index {renderIndex}</p>
        <p>refFromUseRef {refFromUseRef.current}</p>
        <p>refFromCreateRed {refFromCreateRed.current}</p>
        <button onClick={() => { setRenderIndex(p=>p+1)}}>a</button>
    </>
}
ReactDOM.render(
    <App />,
    document.getElementById('root')
);

手动实现createRef和useRef的建议代码如下:

代码语言:javascript
复制
const createRef = ()=>{
    return { current: null }
}

let obj = { current: null }

const useRef = ()=>{
    return obj
}

再看一个例子:

代码语言:javascript
复制
const App = ()=>{
    const [count, setCount] = useState(0);
    function handleAlertClick(){
        setTimeout(()=>{
            alert(count)
        },3000);
    }
    return <div>
        <p>你点击了{count}次</p>
        <button onClick={()=>setCount(count+1)}>click me</button>
        <button onClick={handleAlertClick}> show Alert</button>
    </div>
}
ReactDOM.render(
    <App />,
    document.getElementById('root')
);

点击第一个按钮连续点击,在点击过程中顺便点击Alert按钮,此时发现弹出的数字和count不同步,该如何呢?

代码语言:javascript
复制
const App = ()=>{
    const [count, setCount] = useState(0);
    const lastCount = useRef(count);
    useEffect(()=>{
      lastCount.current = count;  
    })
    function handleAlertClick(){
        setTimeout(()=>{
            alert(lastCount.current)
        },3000);
    }
    return <div>
        <p>你点击了{count}次</p>
        <button onClick={()=>setCount(count+1)}>click me</button>
        <button onClick={handleAlertClick}> show Alert</button>
    </div>
}
ReactDOM.render(
    <App />,
    document.getElementById('root')
);

此时count的值会显示最终的count值了。上面的代码,我们将lastCount.current指向count,这样在访问lastCount.current

时就会访问最新的count。

以上便是createRef和useRef的区别了,希望对你有所帮助。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档