如何在 React 状态更新上加载主屏幕时删除警告



加载主屏幕时,控制台中记录了烦人的警告。如何删除此警告,我已经创建了一个 constisMounted = useRef(null);它是如何工作的,我应该在哪里使用它?

isMounted.current = true;
return () => {
// executed when unmount
isMounted.current = false;
}

警告:无法对未挂载的组件执行 React 状态更新。这是无操作,但它表示应用程序中存在内存泄漏。若要解决此问题,请取消 useEffect 清理函数中的所有订阅和异步任务。 in Home(由Context.Consumer创建( 在路由中(在应用程序.js:21( 在 Switch 中 (在应用.js:20( 在路由器中(由浏览器路由器创建( 在浏览器路由器中 (在 App.js:17( 在应用程序中

Home.js

const isMounted = useRef(null);
useEffect(() => {
const fetchData = async () => {
try {
const res = await Axios.get('http://localhost:8000/service/players');
setPlayerList(res.data.players);
setSearchResults(res.data.players);
showDeleteIcon(privilege);
} catch (e) {
console.log(e);
}
}
fetchData();
}, []);

如果isMountedref,您可以使用第二个效果来更新值。然后,在调用setState之前,您可以检查isMounted.current以查看是否仍处于挂载状态。

const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => isMounted.current = false;
}, []);
useEffect(() => {
const fetchData = async () => {
try {
const res = await Axios.get('http://localhost:8000/service/players');
if (isMounted.current) {
setPlayerList(res.data.players);
setSearchResults(res.data.players);
showDeleteIcon(privilege);
}
} catch (e) {
console.log(e);
}
}
fetchData();
}, []);

.current属性只是 React 引用的工作方式。我真的不确定他们为什么这样做,但本质上这就是你获得/设置值的方式。它与状态不同,因为状态更改会导致重新渲染,而 ref 更新则不会。

不需要 ref 和新效果的更好方法可能是使用状态设置器的回调版本,因为如果组件被卸载,React 可能会避免调用你的回调:

useEffect(() => {
const fetchData = async () => {
try {
const res = await Axios.get('http://localhost:8000/service/players');
setPlayerList(() => res.data.players);
setSearchResults(() => res.data.players);
showDeleteIcon(() => privilege);
} catch (e) {
console.log(e);
}
}
fetchData();
}, []);

最新更新