2 回答

TA貢獻1784條經驗 獲得超8個贊
我想我應該展示如何將其提取到自定義掛鉤中。
function useHasUnmountedRef() {
? const hasUnmountedRef = useRef(false);
? useEffect(() => {
? ? return () => {
? ? ? hasUnmountedRef.current = true;
? ? }
? }, []);
? return hasUnmountedRef;
}
function Form() {
? const hasUnmountedRef = useHasUnmountedRef();
? const handleSubmit = async () => {
? ? await asyncStuff();
? ? if (hasUnmountedRef.current) {
? ? ? // escape early because component has unmounted
? ? ? return;
? ? }
? ? // Thanks to the guard clause above, you can guarantee at this
? ? // point that your component is still mounted. You can perform
? ? // state updates without generating a React warning.?
? ? //
? ? // If you do another "await" however, you will need to check
? ? // again. Everytime you await something async, there is a chance
? ? // that the component could have unmounted while waiting for the
? ? // async stuff to complete.
? };
? return (
? ? <form onSubmit={handleSubmit} />
? );
}
export default Form;

TA貢獻1943條經驗 獲得超7個贊
您可以React.useRef為此使用:
在您的組件中:
const hasUnmounted = React.useRef(false);
React.useEffect(() => {
// maybe you have your side effects here, so you can use the boolean to avoid
// state updates when the component is unmounted
if(!hasUnmounted.current) {
// do state update
}
return () => {
hasUnmounted.current = true;
}
}, [])
React.useRef適合解決這個問題,因為它與更改組件的狀態非常不同,這有點像類組件中的實例變量,更改它不會觸發重新渲染。
添加回答
舉報