正如指南所说,
效果挂钩useEffect增加了从功能组件执行副作用的能力.它的用途与React类中的componentDidMount、componentDidUpdate和componentWillUnmount相同,但统一为一个API.
在本指南中的示例中,预期count
仅在初始渲染时为0:
const [count, setCount] = useState(0);
因此,它将作为componentDidUpdate
加上额外的判断:
useEffect(() => {
if (count)
document.title = `You clicked ${count} times`;
}, [count]);
这就是可以代替useEffect
的定制钩子的基本工作原理:
function useDidUpdateEffect(fn, inputs) {
const didMountRef = useRef(false);
useEffect(() => {
if (didMountRef.current) {
return fn();
}
didMountRef.current = true;
}, inputs);
}
由于@Tholle建议useRef
而不是setState
,因此获得了奖励.