我使用随机用户 api 通过 setInterval 函数获取用户信息,我的 useEffect 如下所示;
// Users.js
useEffect(() => {
const getUser = () => {
fetch("https://randomuser.me/api")
.then((res) => res.json())
.then((data) =>
setUsers((prevUsers) => {
return setUsers([
...prevUsers,
{ key: data.results[0].login.uuid, value: data.results[0] },
]);
})
);
console.log("cleanup?");
};
getUser();
// const userInterval = setInterval(getUser, 5000);
// return () => clearInterval(userInterval);
}, []);
我使用反应导航在另一个页面中显示每个用户的详细信息并像这样导航;
<TouchableOpacity
onPress={() => navigation.navigate("userDetails", item.value)}>
所以当我导航到详细信息页面时,useEffect 不会返回,这意味着组件不会卸载。实际上,由于堆栈导航,页面基本上位于每个页面的顶部并且仍在运行。那么在这种情况下如何停止我的间隔函数?
答案 0 :(得分:1)
react-navigation 的文档中涵盖了这些场景。
来自the docs:
<块引用>React Navigation 向订阅的屏幕组件发出事件 他们。我们可以通过监听 focus 和 blur 事件来了解屏幕何时出现 分别进入焦点或失焦。
示例:
function Profile({ navigation }) {
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// Screen was focused
// Do something
});
return unsubscribe;
}, [navigation]);
return <ProfileContent />;
}
或者借助 useFocusEffect
钩子可以简化上面的代码。
import { useFocusEffect } from '@react-navigation/native';
function Profile() {
useFocusEffect(
React.useCallback(() => {
// Do something when the screen is focused
return () => {
// Do something when the screen is unfocused
// Useful for cleanup functions
};
}, [])
);
return <ProfileContent />;
}