📅  最后修改于: 2022-03-11 15:02:57.184000             🧑  作者: Mango
export default function MyComponent() {
const [loading, setLoading] = useState(false);
const [someData, setSomeData] = useState({});
let componentMounted = true; // (3) component is mounted
// ...
useEffect(() => {
setLoading(true);
someResponse = await doVeryLongRequest(); // it needs some time
// When request is finished:
if (componentMounted){ // (5) is component still mounted?
setSomeData(someResponse.data); // (1) write data to state
setLoading(false); // (2) write some value to state
}
return () => { // This code runs when component is unmounted
componentMounted = false; // (4) set it to false if we leave the page
}
}, []);
return (
{someData}
Go away from here!
);
}