react-native - 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>
);
};
从background
AppState 到active
时,会出现锁定视图,但不是立即生效,后面的当前视图可见一小会儿...
我该如何改进以避免任何“闪烁”,并确保来自background
AppState 时当前内容不可见?
谢谢 !
解决方案
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();
};
}, []);
推荐阅读
- python - 读取 Http 流
- c++ - 包装枚举集
- vb.net - 如何在VB.NET中添加一键播放两个声音文件
- javascript - SWT 浏览器小部件:如何监听 JavaScript 事件?
- c# - log4net 上下文设置。如何向任务并行库生成的子线程传播上下文
- python-3.x - Selenium 失败并显示“此会话将忽略 TLS 证书错误”(在 python 中),如何解决?
- javascript - jwt.verify 在令牌过期时也返回 res
- c# - 在应用 CSS 之后,在操作返回之前获取所有在视口内可见的 HTML
- excel - 为什么复制和粘贴值比使单元格值等于其他单元格值更快?
- c# - 由于以下错误,检索具有 CLSID 的组件的 COM 类工厂失败:8000401a