美文网首页前端学习
React Hooks 异步报错

React Hooks 异步报错

作者: 小盐_814e | 来源:发表于2020-09-14 13:21 被阅读0次

    使用asyncImportComp异步加载路由时报错

    Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup [function.in](http://function.in/) Notification
    
    

    我对hooks也不太了解,网上查了下
    来源:https://blog.csdn.net/sinat_17775997/article/details/102671301

    从网上找了下解决方法

    // 省略组件其他内容,只列出 diff
    useEffect(() => {
        let isUnmounted = false;
        (async () => {
            const res = await fetch(SOME_API);
            const data = await res.json();
            if (!isUnmounted) {
                setValue(data.value);
                setLoading(false);
            }
        })();
     
        return () => {
            isUnmounted = true;
        }
    }, []);
    
    

    我的代码修改后

    // asyncImportComp.js
    import React, { useState, useEffect } from 'react'
    
    const asyncImportComponent = function (importComp) {
      function AsyncComponent(props) {
        const [Comp, setComp] = useState(null)
        useEffect(() => {
          let isUnmounted = false;
          const fetchComponent = async() => {
            try {
              const { default: importComponent } = await importComp();
              if (!isUnmounted){
                setComp(() => importComponent)
              }
            } catch (e) {
              throw new Error('加载组件出错')
            }
          }
    
          fetchComponent();
          return () => {
    
            isUnmounted = true;
          }
        }, [])
        return (
          Comp ? <Comp {...props} /> : <div>加载中...</div>
        )
      }
      return AsyncComponent
    }
    
    export default asyncImportComponent
    
    

    警告消失

    相关文章

      网友评论

        本文标题:React Hooks 异步报错

        本文链接:https://www.haomeiwen.com/subject/zwczektx.html