react-native - Expo React Native 进入视图时执行函数
问题描述
我试图在视图处于前台时执行一个函数,但不是在每次更新组件时执行一次。如果用户导航到另一个视图并返回到第一个视图,它应该再次执行该功能,但只执行一次。有针对这个的解决方法吗?
如果使用不带第二个参数的 useEffect 它会在每次更新时执行,如果我添加 [] 作为第二个参数,它只会在第一次呈现视图时执行,但在导航回视图时不会执行。任何帮助表示赞赏!
解决方案
如果您使用的是react-navigation,您可以通过在屏幕焦点上收听来做到这一点,请参见此处
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// The screen is focused
// Call any action
});
// Return the function to unsubscribe from the event so it gets removed on unmount
return unsubscribe;
}, [navigation]);
推荐阅读
- javascript - Snipcart v3 使用 JavaScript SDK 添加项目
- javascript - new Function() 如何初始化这个
- reactjs - 在函数式反应中传递函数
- nginx - nginx代理子目录到同一台机器上的子域
- python - 我想删除最后一项 discord.py
- java - 如何告诉 Swagger V3 我的“Java 日期”只是一个“日期”,而不是“日期时间”?
- javascript - 将 node_module css 文件导入 NextJs
- android - 如何管理 html 字体大小,以便对 iOS 和 Android 进行相同的解析
- sql - 子查询中是否需要 FOR UPDATE?
- c# - 为什么当我通过 POST API 调用将时间发送到后端时,会额外增加 5 个小时?