首页 > 解决方案 > ReactNative - 如何立即更新视图

问题描述

当应用程序处于后台时,我试图隐藏当前屏幕;我目前使用“AppState”来检测应用程序何时处于后台(或进入前台)并强制图层出现在视图顶部。

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

结果,有这样的片段:

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 时当前内容不可见?

谢谢 !

标签: react-nativeviewstate

解决方案


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();
    };
  }, []);

推荐阅读