zah*_*hay 5 react-native expo react-native-deep-linking expo-linking
React Native包expo-linking有一个名为 的钩子,useURL当应用程序在后台运行时,该钩子对我不起作用。从文档来看,Returns the initial URL followed by any subsequent changes to the URL.我的托管博览会应用程序遇到的问题是,当应用程序已在后台打开时,挂钩不起作用。这是钩子:
export default function App() {
const isLoadingComplete = useCachedResources();
const url = Linking.useURL();
useEffect(() => {
Alert.alert(url ? url.substring(20) : 'null');
}, [url]);
if (!isLoadingComplete) {
return null;
} else {
return (
...
);
}
}
Run Code Online (Sandbox Code Playgroud)
exp://exp.host/@myprofile/myproject?a=b如果我在应用程序关闭时打开 URL ,我会按预期收到警报。如果应用程序在后台运行,则警报不会响起。我已经在 iOS 模拟器和物理 Android 上进行了测试。有什么解决办法吗?请注意,类似的问题也发生在Linking.addEventListener().
小智 1
您可以使用:
import { AppState } from 'react-native';
Run Code Online (Sandbox Code Playgroud)
AppState 是 React Native 提供的一个模块,允许您访问和订阅应用程序生命周期状态的更改。应用程序可以处于各种状态,例如在前台时处于“活动”状态,在后台运行时处于“后台”状态,或者在状态之间转换时处于“非活动”状态。
const hasEventListener = useRef(false);
useEffect(() => {
if (!hasEventListener.current) {
const subscription = AppState.addEventListener('change', nextAppState => {
if (nextAppState === 'active') {
Alert.alert(url ? url.substring(20) : 'null');
}
});
return () => {
subscription.remove();
hasEventListener.current = false;
};
}
}, [url]);
Run Code Online (Sandbox Code Playgroud)
hasEventListener 变量用于确保 AppState 更改的事件侦听器仅添加一次。
| 归档时间: |
|
| 查看次数: |
1445 次 |
| 最近记录: |