如何在我的应用程序中设置状态时修复内存泄漏



我目前正在研究一个音乐应用程序,并且在从详细信息页面导航时遇到内存泄漏错误消息。

当我使用后退按钮导航回我的主页时,我在控制台中得到这个错误消息。

index.js:1 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.

如何解决这个问题?在过去使用React时,我没有处理过任何代码清理。

ConcertDetails.js

import React, { useState, useEffect } from 'react';
import axios from '../utils/API';
const ConcertDetails = (Props) => {
const [details, setDetails] = useState({});
const [songs, setSongs] = useState([]);
useEffect(() => {
const url = '/concerts/' + Props.match.params.id.toString() + '/';
const getDetails = async () => {
const response = await axios.get(url, {}, {'Content-Type': 'application/json'});
setDetails(response.data);
setSongs(response.data.song);
};
getDetails();
});
const getSongs = () => {
return songs.map((song) => (
<li key={song.title}>{song.title}</li>
));
}
return (
<>
<h1>Concert Details</h1>
<p>Venue: {details.venue}</p>
<p>Date: {details.date}</p>
<ul>
{getSongs()}
</ul>
</>
)
}
export default ConcertDetails;

App.js

import React from 'react';
import './App.css';
import NavBar from "./components/Navbar";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Home from './pages';
import About from './pages/about';
import Contact from './pages/contact';
import SignUp from './pages/signup';
import SignIn from './pages/signin';
import ConcertDetails from './pages/concertDetails';
function App() {
return (
<Router>
<NavBar />
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route path="/signin" component={SignIn} />
<Route path="/signup" component={SignUp} />
<Route path="/concert/:id" component={ConcertDetails} />
</Switch>
</Router>
);
}
export default App;

你想只在第一个组件渲染时运行useEffect。添加[]作为useEffect的第二个参数

useEffect(() => {
const url = '/concerts/' + Props.match.params.id.toString() + '/';
const getDetails = async () => {
const response = await axios.get(url, {}, {'Content-Type': 'application/json'});
setDetails(response.data);
setSongs(response.data.song);
};
getDetails();
}, []);

没有第二个参数的。每次state/props改变时,效果都会运行。由于效果改变了状态,这可能会导致无限循环。

检查plnkr: CodeSanbox: https://codesandbox.io/s/suspicious-dew-rsz5s?file=/src/App.js

解释:

有很多问题,让我们一步一步解决

  • 你的useEffect运行多次,我们必须定义一个条件与数组的依赖关系,我将定义它只运行在挂载与空的依赖关系。
  • 但是,你的useEffect在异步调用后试图setState。所以,也许在那一刻,组件已经卸载了。出于这个原因,您必须运行safeSetState:)。基本上,你必须在setState之前验证。

首先定义mount/unmounted的钩子验证:

useSafeWrite.js:

import React from 'react';
function useSafeWrite(dispatch) {
const mounted = React.useRef(false)
React.useLayoutEffect(() => {
mounted.current = true
return () => (mounted.current = false)
}, [])
return React.useCallback(
(...args) => (mounted.current ? dispatch(...args) : void 0),
[dispatch],
)
}
export default useSafeWrite;

之后,我们将用钩子重新定义setDetailssetSongs,并在useEffect中使用它们。

ConcertDetails


const [details, setDetails] = useState({});
const [songs, setSongs] = useState([]);
const safeSetDetails = useSafeWrite(setDetails);
const safeSetSongs =  useSafeWrite(setSongs);
useEffect(() => {
const getDetails = async () => {
const url = '/concerts/' + Props.match.params.id.toString() + '/';
const response = await axios.get(url, {}, {'Content-Type': 'application/json'});

safeSetDetails(response.data);
safeSetSongs(response.data.song );
};
getDetails();
}, [safeSetDetails, safeSetSongs]);

CodeSanbox: https://codesandbox.io/s/suspicious-dew-rsz5s?file=/src/App.js

相关内容

  • 没有找到相关文章

最新更新