我已经构建了一个正在运行的应用程序,它应该在用户完成运行后显示用户的运行数据。当跑步者确认他们已经停止跑步时,他们会从“完成屏幕”返回“主屏幕”。
有时,包含用户跑步信息的模式不会弹出,而其他时候,模式会在用户完成跑步后弹出,进入主屏幕,然后进入他们的个人资料屏幕,然后返回主屏幕。
只有当它们来自完成屏幕时,它才会弹出。以下是当前行为的示例:
完成屏幕 => 主屏幕(模式应该会弹出,但有时不会)
完成屏幕 => 主屏幕 => 配置文件屏幕(通过抽屉导航器访问)=> 主屏幕(弹出模式,但不应该)
下面是我的代码:
//主屏幕
import React, { useState, useEffect } from 'react';
import {Alert, BackHandler, Button, Dimensions, Image, SafeAreaView, StyleSheet, StatusBar, ScrollView, Text, TextInput, TouchableOpacity, View, } from 'react-native'
import { useFocusEffect } from '@react-navigation/native'
const HomeScreen = ({navigation, route}) => {
client_instance.assign_navigator(navigation) //server keeps track of user's screen location
const [isModalVisible, setModalVisible] = useState(false);
const toggleModal = () => {
setModalVisible(!isModalVisible);
}
useFocusEffect(
React.useCallback(()=>{
let isActive = true
async function getLocationAsync(){ //function that lives in the useFocusEffect
let {status} = await Location.requestForegroundPermissionsAsync()
if(status !== 'granted'){
setErrorMsg('Permission to access location was denied')
return;
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location)
}
if(route.params?.didComeFromFinishingScreen)
{console.log('didComeFromFinishingScreen is attempting to open modal')
setModalVisible(true)}
return()=>{
console.log('cleanup function is closing modal)
setModalVisible(false)
}
getLocationAsync()
},
[],
),
)
return(
<View>
<Modal isVisible = {isModalVisible}>
<View style = {styles.modal}>
<Text style = { styles.modalText}> {i18n.t('summary')} </Text>
<Text style = { styles.modalText2}> {i18n.t('distance')}: {distance} </Text>
<View style = {styles.modal_view}>
<View style = {styles.button4 }>
<TouchableOpacity
onPress = {toggleModal}
>
<Text style = {[styles.modalText,{ fontSize: height*0.03, color: '#009387', textAlign: 'center', width: width}]}>{i18n.t('continue')}</Text>
</TouchableOpacity>
</View>
</View>
<TouchableOpacity
onPress = {toggleModal}
>
</TouchableOpacity>
</View>
</Modal>
</View>
)
}
//完成画面
const stopRunning = async () => { //This function allows the user to stop running
Alert.alert(
i18n.t('stop2'),
i18n.t('stop3'),
[
{
text: (i18n.t('yes')),
onPress: ( checkConfirm )
},
{
text: i18n.t('no'),
onPress: (null)
}]
)
}
const checkConfirm = async () => { //sends response to the server to stop collecting running info
let response = await client_instance.stop_running()
navigation.navigate('Home', {
didComeFromFinishingScreen: true
})
}
...
<TouchableOpacity
style={styles.button}
onPress={stopRunning}
>
<Text>{i18n.t('stopRun'}</Text>
</TouchableOpacity>