[英]Unmounted component - React Native
我必须使用函数/常量从 API 获取数据:
const [isLoadingRoom, setLoadingRoom] = useState(true);
const [isLoadingLobby, setLoadingLobby] = useState(true);
const [rooms, setRooms] = useState([]);
const [lobbies, setLobbies] = useState([]);
const getRooms = async () => {
let isMounted = true;
async function fetchData() {
const response = await fetch('https://yatzy.live/functions/api/getRooms.php');
const json = await response.json();
// 👇️ only update state if component is mounted
if (isMounted) {
setRooms(json);
setLoadingRoom(false);
}
}
fetchData();
return () => {
isMounted = false;
}
}
const getLobbies = async () => {
let isMounted = true;
async function fetchData() {
const response = await fetch('https://yatzy.live/functions/api/getLobbies.php');
const json = await response.json();
// 👇️ only update state if component is mounted
if (isMounted) {
setLobbies(json);
setLoadingLobby(false);
}
}
fetchData();
return () => {
isMounted = false;
}
}
useEffect(() => {
const roomInterval = setInterval(() => {
getRooms();
getLobbies();
}, 5000);
return () => clearInterval(roomInterval);
}, []);
API 每 5 秒获取一次数据,但过了一会儿我收到以下消息:
警告:无法对未安装的组件执行 React state 更新。 这是一个无操作,但它表明您的应用程序中存在 memory 泄漏。 要修复此问题,请在 useEffect 清理 function 中取消所有订阅和异步任务。
我尝试了不同的方法来获取带有 const、函数、异步等的 API,但我还是收到了这个错误消息。有什么提示吗?
useRef 而不是普通变量:
const isMountedRef = useRef(true);
useEffect(() => {
const roomInterval = setInterval(() => {
getRooms();
getLobbies();
}, 5000);
return () => {
clearInterval(roomInterval);
isMountedRef.current = false;
};
}, []);
并将检查条件更改为
if(isMountedRef.current){
// execute setState
}
希望能帮助到你。 随时怀疑
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.