【问题标题】:React.js useEffect with nested async functions带有嵌套异步函数的 React.js useEffect
【发布时间】:2021-03-21 08:43:37
【问题描述】:

我在加载我的网络应用程序时显示常见警告,但再也没有出现...

警告:无法对未安装的组件执行 React 状态更新。 这是一个空操作,但它表明您的应用程序中存在内存泄漏。 要修复,请取消 useEffect 中的所有订阅和异步任务 清理功能。

编辑**** 它是由这段代码引起的。我已将其缩小到一个功能。当我尝试设置水分状态时它会爆炸。我不知道为什么。

function getData (){
    Axios.get("http://localhost:3001/api/get-value").then((response) => {
        const recievedData = response.data;
        const dataValue = recievedData.map((val) => {
            return [val.value]
        })
        if (loading === true){
            setLoading(false);
        }
        return parseInt(dataValue);
    }).then((resp)=>setMoisture(resp))
}

React.useEffect(() => {
    if (moisture === "initialState"){
        getData();
    }
}, []); 

【问题讨论】:

  • 我想我已将问题范围缩小到 getData 函数内。
  • setMoisture() 是做什么的?那里使用了任何组件?
  • 是的,它是一个状态变量 [moisture, setMoisture] = useState['']
  • 我已经编辑了我之前的帖子。这就是导致问题的原因。知道如何解决这个问题吗?我调用 setLoading 也是一个状态变量,没有问题
  • 你见过这个问题吗?我觉得你的情况也差不多。 stackoverflow.com/questions/56442582/… 确保返回一个在 useEffect 末尾进行清理的函数。类似return () => { ... };

标签: javascript reactjs asynchronous react-hooks use-effect


【解决方案1】:

为了完整起见,在此处发布答案(基于 cmets)。

基本上,在 useEffect() 结束时使用局部变量和清理函数。以此为参考:

Similar situation here

【讨论】:

    【解决方案2】:

    您应该在 useEffect 中声明该函数或将其添加为依赖项。一种方法就是将你的函数移动到钩子内。

      // I assumed that your useState hooks looks something similar.
      const [moisture, setMoisture] = React.useState('initialState')
      const [loading, setLoading] = React.useState(true)
    
      React.useEffect(() => {
        function getData() {
          Axios.get("http://localhost:3001/api/get-value").then((response) => {
            const recievedData = response.data;
            const dataValue = recievedData.map((val) => {
              return [val.value]
            })
            if(loading === true) {
              setLoading(false);
            }
            return parseInt(dataValue);
          }).then((resp => setMoisture(resp)))
        }
    
        if (moisture === "initialState"){
          getData();
        }
    
      }, [])
    

    您可能还想先将数据设置为状态,然后将加载状态更改为 false,这样可以防止一些错误。这是另一种管理加载状态和承诺的方法

      React.useEffect(() => {
        function getData() {
          setLoading(true)
          Axios.get("http://localhost:3001/api/get-value")
            .then((response) => {
              const dataValue = response.data.map((val) => {
                return [val.value]
              })
              // This is going to pass 0 when can't parse the data
              setMoisture(parseInt(dataValue) || 0)
              setLoading(false)
            })
        }
    
        getData()
      }, [])
    

    【讨论】:

      猜你喜欢
      • 2012-10-12
      • 2014-10-05
      • 2019-10-02
      • 2018-06-27
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      相关资源
      最近更新 更多