使用useRef跨渲染周期保存数据

useRef 可以用来获取组件实例对象或者是 DOM 对象,而它还有跨渲染周期保存数据的作用。

通常用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React, { useState, useEffect, useMemo, useRef } from 'react';

export default functionApp (props) {
const [count, setCount] = useState(0);
const doubleCount = useMemo(() => {
return 2* count;
}, [count]);

const couterRef = useRef();

useEffect(() => {
document.title = `The value is ${count}` ;
console.log(couterRef.current);
}, [count]);

return (
<>
<button ref={couterRef} onClick={() => {setCount(count + 1)}}>Count: {count}, double: {doubleCount}</button>
</>
);
}

代码中用useRef创建了couterRef对象,并将其赋给了buttonref属性。这样,通过访问couterRef.current就可以访问到button对应的DOM对象。

使用useRef保存数据

在一个组件中有什么东西可以跨渲染周期,也就是在组件被多次渲染之后依旧不变的属性?没错,是state。一个组件的 state 可以在多次渲染之后依旧不变。
但是,state的问题在于一旦修改了它就会造成组件的重新渲染。
那么这个时候就可以使用 useRef 来跨越渲染周期存储数据,而且对它修改也不会引起组件渲染。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
importReact, { useState, useEffect, useMemo, useRef } from'react';

export default functionApp (props) {
const [count, setCount] = useState(0);
const doubleCount = useMemo(() => {
return 2* count;
}, [count]);

const timerID = useRef();

useEffect(() => {
timerID.current = setInterval(() => {
setCount(count => count + 1);
}, 1000);
}, []);

useEffect(() => {
if(count > 10){
clearInterval(timerID.current);
}
});

return (
<>
<button ref= {couterRef} onClick={() => {setCount(count + 1)}}>Count: {count}, double: {doubleCount}</button>
</>
);

}

在上面的例子中,使用了ref对象的current属性来存储定时器的ID,这样便可以在多次渲染之后依旧保存定时器ID,从而能正常清除定时器。