Уничтожить React Native Component On Blur - PullRequest
0 голосов
/ 12 марта 2020

У меня следующая структура навигации

const AppNavigator = createStackNavigator({
    AppSplashScreen: AppSplashScreen,
    WalkthroughScreen: WalkthroughScreen,
    LoginScreen: LoginScreen,
    BottomTabNavigator: BottomTabNavigator
}, {
    headerMode: 'none',
    cardStyle: { backgroundColor: '#000000' },
});

И вот мой первый экран. Я использую видео для отображения spla sh экранной анимации

export default class AppSplashScreen extends Component {

    state = {
        displayVideoPlayer: true,
        firstLaunch: false
    }

    componentDidMount() {
        SplashScreen.hide();
    }

    componentWillUnmount() {
        this.setState({
            displayVideoPlayer: false
        });
    }

    isFirstLaunch() {
        let firstLaunch = true;
        if (true === storage.get('APP_ALREADY_LAUNCHED')) {
            firstLaunch = false;
        } else {
            storage.set('APP_ALREADY_LAUNCHED', true);
            firstLaunch = true;
        }
        return firstLaunch;
    }

    didCompleteVideoPlayback() {
        if (true === this.state.displayVideoPlayer) {
            this.setState({
                displayVideoPlayer: false
            });
        }
        const currentRouteName = this.props.navigation.state.routeName;
        if ('AppSplashScreen' !== currentRouteName) {
            return false;
        }
        if (true === global.SKIP_SPLASH_SCREEN_REDIRECT) {
            return false;
        }
        if (this.isFirstLaunch()) {
            this.props.navigation.navigate('LanguageScreen');
            return false;
        }
        this.props.navigation.navigate('HomeScreen');
    }

    render() {
        return (
            <View style={{flex: 1, backgroundColor: '#000000', alignItems: 'center', justifyContent: 'center'}}>
                {true === this.state.displayVideoPlayer &&
                    <Video
                        source={VIDEO_SPLASH_2}
                        muted={true}
                        repeat={false}
                        playInBackground={false}
                        resizeMode="contain"
                        onEnd={() => this.didCompleteVideoPlayback()}
                        style={{height: '100%', width: '100%', backgroundColor: '#000000'}}
                    />
                }
            </View>
        );
    }
}

Моя проблема заключается в том, что всякий раз, когда я открываю приложение, оно вызывает didCompleteVideoPlayback и пытается выполнить перенаправление, которое конфликтует с перенаправлением другого уровня приложения, например как, перенаправить по щелчку уведомления pu sh или постоянство состояния навигации и т. д. c.

Как убедиться, что если AppSplashScreen не в фокусе, оно не должно отображать видео и не триггер didCompleteVideoPlayback

PS: componentWillUnmount не уничтожает компонент Video из памяти, я хочу убедиться, что

Любой указатель здесь приветствуется.

Спасибо.

1 Ответ

0 голосов
/ 12 марта 2020

Кажется, что он работает со слушателем навигации, вот что я сделал

componentDidMount() {
    SplashScreen.hide();
    this.focusListener = this.props.navigation.addListener('didFocus', () => {
        this.setState({
            isFocussed: true
        })
    });
    this.blurListener = this.props.navigation.addListener('didBlur', () => {
        this.setState({
            isFocussed: false
        })
    });
    setTimeout(() => {
        this.unsubscribeListeners();
    }, 100);
}

render() {
    return (
        <View style={{flex: 1, backgroundColor: '#000000', alignItems: 'center', justifyContent: 'center'}}>
            {true === this.state.isFocussed &&
                <Video
                    source={VIDEO_SPLASH_2}
                    muted={true}
                    repeat={false}
                    playInBackground={false}
                    resizeMode="contain"
                    onEnd={() => this.didCompleteVideoPlayback()}
                    style={{height: '100%', width: '100%', backgroundColor: '#000000'}}
                />
            }
        </View>
    );
}

Я не уверен, что это хороший способ справиться с этим или есть лучший способ сделать это.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...