gpt4 book ai didi

javascript - 无法对 Interval 函数中的未安装组件问题执行 React 状态更新

转载 作者:行者123 更新时间:2023-11-30 13:56:51 25 4
gpt4 key购买 nike

我对带有间隔函数的 componentWillUnmount 有一些问题。所以我在 stackoverflow 和 google 中搜索如何解决这个问题,但是我找不到正确的解决方案。

在我的本地机器上,控制台没有错误,它只显示编译成功,实际上,所有功能都运行良好。但是当我提交到 github 并在 Travis CI 中进行测试时,它显示了一个错误。所以我觉得不太舒服,因为我担心长时间运行这个网络应用程序时会出现内存泄漏。

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 the componentWillUnmount method.

我的间隔函数在 componetDidMount() 中,我添加了 clearInterval(this.interval) 代码来清除我在 componetWillUnmount 中的间隔函数。

我发现我必须在 componentWillUnmount 中编写代码来解决这个问题,但它似乎不起作用。

也可以用这个 URL checkin codeSandBox

[PostContainer.js]

import React, { Component } from 'react';
import DataTable from 'react-data-table-component';
import axios from 'axios';
import { darkTheme, columns } from './tableSetting';

/* Price Comma Function */
function addComma(num) {
let regexp = /\B(?=(\d{3})+(?!\d))/g;
return num.toString().replace(regexp, ',');
}

/* Title Component */
let titleComponent = (
<div className="logoContainer">
<a
href="https://www.bithumb.com/"
target="_blank"
rel="noopener noreferrer">
<img
src="https://github.com/sangumee/Crypto-Table/blob/master/public/images/bithumb.png?raw=true"
alt="bithumb LOGO"
className="logo"
/>
</a>
</div>
);

/* Main Component */
class PostContainer extends Component {
state = {
title: <div className="Load">Load data from API Server...</div>,
status: <div className="initLoading">LOADING WAIT!!</div>,
data: [],
};

/* Error Catch */
componentDidCatch(error, info) {
console.log(error, info);
}

/* ComponentDidMount Cycle */
async componentDidMount() {
/* Exchange Rate USD to KRW */
const exchangeResponse = await axios.get(
`https://quotation-api-cdn.dunamu.com/v1/forex/recent?codes=FRX.KRWUSD`
);
const exchangeData = exchangeResponse.data[0].basePrice;
this.getCoinData(exchangeData); // Initial get coin Data
this.interval = setInterval(() => {
this.getCoinData(exchangeData);
}, 5000); // Interval 5 Seconds
}

componentWillUnmount() {
clearInterval(this.interval);
console.log('componentWillUnmount');
}

async getCoinData(exchangeData) {
let chartData = []; //

let status;
const response = await axios.get(
`https://api.bithumb.com/public/ticker/all`
);
const usdCoinData = await axios.get(
`https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC,ETH,DASH,LTC,ETC,XRP,BCH,XMR,ZEC,QTUM,BTG,EOS,ICX,VET,TRX,ELF,MITH,MCO,OMG,KNC,GNT,ZIL,ETHOS,PAY,WAX,POWR,LRC,GTO,STEEM,STRAT,ZRX,REP,AE,XEM,SNT,ADA,PPT,CTXC,CMT,THETA,WTC,ITC,TRUE,ABT,RNT,PLY,WAVES,LINK,ENJ,PST,SALT,RDN,LOOM,PIVX,INS,BCD,BZNT,XLM,OCN,BSV,TMTG,BAT,WET,XVG,IOST,POLY,HC,ROM,AMO,ETZ,ARN,APIS,MTL,DACC,DAC,BHP,BTT,HDAC,NPXS,AUTO,GXC,ORBS,VALOR,CON,ANKR,MIX&tsyms=USD`
);

/* If API Status Success */
if (response.data.status === '0000') {
delete response.data.data['date']; // Remove 'date' data from object

/* Create table data */
for (let [key, value] of Object.entries(response.data.data)) {
let premiumPrice, premiumPriceGap;
if (typeof usdCoinData.data.DISPLAY[key] === 'undefined') {
// If Coin data not exists set '-'
premiumPrice = premiumPriceGap = '-';
} else {
/* Calculate USD * KRW data */
let usdPrice =
usdCoinData.data.DISPLAY[key].USD.PRICE.replace('$ ', '').replace(
',',
''
) * exchangeData;
premiumPrice = (
((value.sell_price - usdPrice) / usdPrice) *
100
).toFixed(2);
premiumPriceGap = (value.sell_price - usdPrice).toFixed(2);
}
/* Create Final Data */
chartData.push({
key: key,
Price: `${addComma(value.sell_price)}원`,
FluctateRate: `${value['24H_fluctate_rate']}`,
FluctateRate24: `${addComma(value['24H_fluctate'])}`,
premium: addComma(premiumPrice),
premiumGap: addComma(premiumPriceGap),
});
}
/* If Server Status Success */
this.setState({
statue: status,
result: 'success',
data: chartData,
title: (
<div>
{titleComponent}
<div id="statusSuccess">{status}</div>
<p className="apiSuccess"> API Works Fine</p>
</div>
),
});
} else {
/* If Server Status Fails */
this.setState({
statue: status,
result: 'fail',
title: (
<div>
{titleComponent}
<div id="statusFail">{status}</div>
<p className="apiFail"> API is not wokring. Something is Wrong</p>
</div>
),
});
}
}

render() {
const { data, title } = this.state;
// console.log(data);
return (
<DataTable
title={title}
className="Post"
columns={columns}
data={data}
customTheme={darkTheme}
responsive={true}
noDataComponent={this.state.status}
fixedHeader
/>
);
}
}

export default PostContainer;

最佳答案

试试这个方法:


class PostContainer extends Component {

_isMounted = false

...

async componentDidMount() {

this._isMounted = true

/* Exchange Rate USD to KRW */
const exchangeResponse = await axios.get(
`https://quotation-api-cdn.dunamu.com/v1/forex/recent?codes=FRX.KRWUSD`
);

const exchangeData = exchangeResponse.data[0].basePrice;

this.getCoinData(exchangeData); // Initial get coin Data

this.interval = setInterval(() => {
if (this._isMounted) this.getCoinData(exchangeData);
else clearInterval(this.interval)
}, 5000);
}

componentWillUnmount() {
this._isMounted = false
}

}

关于javascript - 无法对 Interval 函数中的未安装组件问题执行 React 状态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57106618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com