简体   繁体   English

React:无法在未安装的组件上执行 React state 更新

[英]React: Can't perform a React state update on an unmounted component

I'm trying to load some json data into my React app and make some modification to the data before using it (adding one more column with additional data to each row of dataset) in order to create a D3.js visualization.我正在尝试将一些 json 数据加载到我的 React 应用程序中,并在使用它之前对数据进行一些修改(向数据集的每一行添加一个带有附加数据的列)以创建 D3.js 可视化。 I managed to get it working and displaying in console.log, but, however, whenever I'm starting to make any changes to my app the following window with an error pops up:我设法让它工作并在console.log中显示,但是,每当我开始对我的应用程序进行任何更改时,都会弹出以下window错误: 在此处输入图像描述

I'm not sure why exactly this is happening.我不确定为什么会发生这种情况。 I tried to apply this modification helper function by adding one more 'await' to fetchUrl() function (something like await addQuarterStringsToArr(data) ) or doing it with fetch API in the main component, but in all those cases I didn't get a desired dataset with an additional column. I tried to apply this modification helper function by adding one more 'await' to fetchUrl() function (something like await addQuarterStringsToArr(data) ) or doing it with fetch API in the main component, but in all those cases I didn't get带有附加列的所需数据集。

Here is my codesandbox这是我的密码箱

Could you please let me know what am I doing wrong here?你能告诉我我在这里做错了什么吗? I'm quite new to React and programming in general, therefore I'm confused on how to resolve this issue.我对 React 和编程很陌生,因此我对如何解决这个问题感到困惑。

Thank you in advance!先感谢您!

If you want to use setState , you need to be sure the component is mounted.如果要使用setState ,则需要确保组件已安装。 You can use the componentDidMount function and do the fetch request inside that function.您可以使用componentDidMount function 并在 function 内部执行获取请求。 https://en.reactjs.org/docs/react-component.html#componentdidmount https://en.reactjs.org/docs/react-component.html#componentdidmount

Remember to also abort the request when the component is unmounted using the componentWillUnmount function.请记住,在使用componentWillUnmount function 卸载组件时也要中止请求。 https://en.reactjs.org/docs/react-component.html#componentwillunmount https://en.reactjs.org/docs/react-component.html#componentwillunmount

What's happening is that you are either doing the fetch request and it calls setState before the component is mounted OR you do the fetch request and the component was unmounted before the fetch request finished (or both things happening)发生的情况是,您要么正在执行 fetch 请求并且它在安装组件之前调用setState ,要么您执行 fetch 请求并且在 fetch 请求完成之前卸载了组件(或两者都发生)

You need to do something similar to this.你需要做类似的事情。

import { useEffect, useState } from 'react';


const useFetch = (url) => {
    const [response, setResponse] = useState(null);
    const [loading, setLoading] = useState(false);
    const [hasError, setHasError] = useState(false);

    useEffect(() => {
        setLoading(true);
        fetch(
            url,{
            method: 'GET',
        }).then(res => {
            setResponse(res);
            setLoading(false);
        })
        .catch(() => {
            setHasError(true);
            setLoading(false);
        });
    }, [url]);
    return [response, loading, hasError];
};
export default useFetch;


to make use of this.利用这一点。

import { useEffect, useState } from 'react';
const component = () => {
     const [response, loading, hasError] = useFetch('http://myurl.com/api/post');

useEffect(() => {
    if(response !== null){ 
      console.log(response);
    }
});

   return <>
     {loading && <span>loading</span> }
     {hasError && <span>Some error!!!</span>} 
     <div> {JSON.stringify(response)} </div>
   </>;
}


I would rather use a useReducer but in this case since, you are requesting Hooks.我宁愿使用 useReducer 但在这种情况下,您正在请求 Hooks。 Here is my better approach to what you've done so far.这是我迄今为止所做的更好的方法。

you are not returning data from addQuarterStringsToArr function that why here setData(addQuarterStringsToArr(data)) going to be undefined.你没有从addQuarterStringsToArr function 返回数据,为什么这里setData(addQuarterStringsToArr(data))将是未定义的。

just return dataset in addQuarterStringsToArr function like this:只需在addQuarterStringsToArr function 中返回数据集,如下所示:

// helper function to add corresponding text for the quarter and year as a string
export default function addQuarterStringsToArr(dataset) {
  for (let i = 0; i < dataset.length; i++) {
    switch (dataset[i][0].substring(5, 7)) {
      case "01":
      case "02":
      case "03":
        dataset[i].push(dataset[i][0].substring(0, 4) + " Q1");
        break;
      case "04":
      case "05":
      case "06":
        dataset[i].push(dataset[i][0].substring(0, 4) + " Q2");
        break;
      case "07":
      case "08":
      case "09":
        dataset[i].push(dataset[i][0].substring(0, 4) + " Q3");
        break;
      case "10":
      case "11":
      case "12":
        dataset[i].push(dataset[i][0].substring(0, 4) + " Q4");
        break;
      default:
        break;
    }
  }
  return dataset;
}

hope this do the work.希望这能奏效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React - 无法在未安装的组件上执行 React state 更新 - React - Can't perform a React state update on an unmounted component React Can't perform a React state update on an unmounted component error - React Can't perform a React state update on an unmounted component error React Native:无法对未安装的组件执行 React state 更新 - React Native: Can't perform a React state update on an unmounted component React 导致:无法对未安装的组件执行 React state 更新 - React causing: Can't perform a React state update on an unmounted component 导航问题 - 无法对卸载的组件执行 React 状态更新 - Navigation issue - can't perform a React state update on unmounted component 如何解决“无法对未安装的组件执行反应状态更新” - How to solve "can't perform a react state update on an unmounted component" 无法在未安装的组件主题提供程序上执行 React state 更新 - Can't perform a React state update on an unmounted component theme provider 无法使用 useEffect 挂钩对未安装的组件执行 React state 更新 - Can't perform a React state update on an unmounted component with useEffect hook 如何修复无法在未安装的组件上执行 React state 更新 - How to fix Can't perform a React state update on an unmounted component 无法对 setInterval 的未安装组件执行 React state 更新 - Can't perform a React state update on an unmounted component for setInterval
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM