ReactNative -如何即时更新视图



当应用程序在后台时,我试图隐藏当前屏幕;我目前使用的是appstate。检测应用程序何时在后台(或进入前台),并强制一个图层出现在视图的顶部。

到目前为止,我被2个ReactNative限制所困:

  • 首先,Android上的AppState只有background状态,没有inactive状态。所以,在进入后台之前,应用程序不能应用新的状态(只有当进入前台时)。
  • 第二,setstate的异步工作方式。更新不会立即应用。

因此,使用如下代码段:

import React from 'react';
import {AppState, Button, Text, View} from 'react-native';
const App: () => Node = () => {
const appState = React.useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] = React.useState(appState.current);
const [lockVisible, setLockVisible] = React.useState(false);
useEffect(() => {
const subscription = AppState.addEventListener('change', nextAppState => {
if (appState.current.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!');
setLockVisible(true);
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
console.log('AppState', appState.current);
});
return () => {
subscription.remove();
};
}, []);
return (
<View style={{flex: 1}}>
<View style={{flex: 1}}>
<Text>Current Content</Text>
</View>
{lockVisible && (
<View style={{
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
backgroundColor: '#f00',
}}>
<Text>LOCKED !</Text>
<Button title={'OPEN'} onPress={() => {setLockVisible(false)}} />
</View>
)}
</View>
);
};

当从backgroundAppState到active时,视图出现,但它不是立即生效,后面的当前视图在一段时间内是可见的…

如何改进以避免任何"闪烁",并确保当前内容在来自backgroundAppState时不可见?

谢谢!

如果我改变background事件的状态而不是come back to foreground事件,它就不会再闪烁了。

useEffect(() => {
const subscription = AppState.addEventListener('change', nextAppState => {
if (appState.current.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!');
}
if (nextAppState === 'active') { // <- here is the "fix"
setLockVisible(true);
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
console.log('AppState', appState.current);
});
return () => {
subscription.remove();
};
}, []);

最新更新