我使用常规状态变量而不是 ref。
// Initializing didMount as false
const [didMount, setDidMount] = useState(false)
// Setting didMount to true upon mounting
useEffect(() => { setDidMount(true) }, [])
// Now that we have a variable that tells us wether or not the component has
// mounted we can change the behavior of the other effect based on that
const [count, setCount] = useState(0)
useEffect(() => {
if (didMount) document.title = `You clicked ${count} times`
}, [count])
我们可以像这样将 didMount 逻辑重构为自定义钩子。
function useDidMount() {
const [didMount, setDidMount] = useState(false)
useEffect(() => { setDidMount(true) }, [])
return didMount
}
最后,我们可以像这样在我们的组件中使用它。
const didMount = useDidMount()
const [count, setCount] = useState(0)
useEffect(() => {
if (didMount) document.title = `You clicked ${count} times`
}, [count])
更新使用 useRef 挂钩来避免额外的重新渲染(感谢@TomEsterez 的建议)
这次我们的自定义钩子返回一个函数,返回我们的 ref 的当前值。你也可以直接使用 ref,但我更喜欢这个。
function useDidMount() {
const mountRef = useRef(false);
useEffect(() => { mountRef.current = true }, []);
return () => mountRef.current;
}
用法
const MyComponent = () => {
const didMount = useDidMount();
useEffect(() => {
if (didMount()) // do something
else // do something else
})
return (
<div>something</div>
);
}
附带说明一下,我从来没有使用过这个钩子,并且可能有更好的方法来处理它,这将更符合 React 编程模型。