如指南所述,
效果挂钩(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)
fn();
else
didMountRef.current = true;
}, inputs);
}
致谢@Tholle useRef
而不是进行建议setState
。