一、useRef仅仅能用于FunctionComponent组件, 而createRef既能用于FunctionComponent, 又能用于ClassComponent组件。
二、createRef每次渲染都会返回一个新的引用,而useRef每次都会返回相同的引用
import React, { createRef, useRef, useState } from ‘react’;
const Distinguish = () => {
const [index, setIndex] = useState
const refUseRef = useRef
const refCreateRef = createRef
if (!refUseRef.current) {
refUseRef.current = index;
}
if (!refCreateRef.current) {
// @ts-ignore
refCreateRef.current = index;
}
return (
当前 render index: {index}
refUseRef: {refUseRef.current}
refCreateRef: {refCreateRef.current}
);
};
export default Distinguish;
每次点击按钮,当前index和refCreateRef都是一样,值会增加,而refUseRef的值一直是初始化时候的值,为什么呢?
因为createRef会随着FunctionComponent重复执行而不断被初始化,而在ClassComponent中,只有在componentDidMount方法时才初始化。
三、useRef可以用来自定previous
const usePrevious = (state) => {
const ref = useRef();
useEffect(() => {
ref.current = state;
});
return ref.current;
};
这样就可以实现类似classComponent中的componentDidUpdate中的prevProps中的值了