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适合解决这个问题,因为它与更改组件的状态非常不同,这有点像类组件中的实例变量,更改它不会触发重新渲染。
添加回答
举报