📅  最后修改于: 2022-03-11 15:04:05.453000             🧑  作者: Mango
// custom Hook for automatic abortion on unmount or dependency change
// You might add onFailure for promise errors as well.
function useAsync(asyncFn, onSuccess) {
useEffect(() => {
let isActive = true;
asyncFn().then(data => {
if (isActive) onSuccess(data)
else console.log("aborted setState on unmounted component")
});
return () => {
isActive = false;
};
}, [asyncFn, onSuccess]);
}
const Child = () => {
const [state, setState] = useState("loading (4 sec)...");
useAsync(simulateFetchData, setState);
return Child: {state};
};
const Parent = () => {
const [mounted, setMounted] = useState(true);
return (
Parent:
{mounted && }
Unmount Child, while it is still loading. It won't set state later on,
so no error is triggered.
);
};
const simulateFetchData = () => new Promise(
resolve => setTimeout(() => resolve("data fetched"), 4000));
ReactDOM.render( , document.getElementById("root"));