📌  相关文章
📜  无法对未安装的组件执行 React 状态更新 - 无论代码示例

📅  最后修改于: 2022-03-11 14:55:35.884000             🧑  作者: Mango

代码示例4
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!
); }