首页 > 解决方案 > 如何导航?(未定义不是对象(评估“this.props”)

问题描述

我正在尝试导航到其他屏幕,并且正在使用类组件。当我将输入数据保存到 MySQL 时,我想导航到名为“Map”的屏幕。我尝试了我知道的方法,但最后我无法导航。

我正在尝试从 AAddBinScreen 导航到 MapScreen(我有这个名为“地图”的屏幕)。

这是我的 AABinScreen 代码:

constructor() {
       super();

       this.state = {
           ...
       }
       this.goMap = this.goMap.bind();
       
   }

   pressAdd(){
       const check = this.saveData();
       if(check == true){
           Alert.alert("Kayıt başarıyla eklendi.")
           setTimeout(this.goMap(), 800);
       }        
   }

   goMap() {
       this.params.navigation.navigate('Map');
   }

这是我的按钮。

render() {
        return (
            <SafeAreaView style={styles.container}>
                <ScrollView>
                     ...
                     ...
                    <TouchableOpacity disabled={this.state.disabled} 
                                      activeOpacity={0.8} style={styles.Btn} 
                                      onPress={()=>this.pressAdd()}>
                        <Text style={styles.btnText}>EKLE</Text>
                    </TouchableOpacity>

                </ScrollView>
            </SafeAreaView>
        );
    }
}
module.exports = AAddBinScreen;

还有我的 app.js

const navigator = createStackNavigator({
    ...
    Map: {
        screen: MapScreen,
        navigationOptions:{
            headerShown:false
        }
    },
    ...
}, {
    initialRouteName: 'Login',
});

export default createAppContainer(navigator);

标签: reactjsreact-nativereact-native-android

解决方案


您可以尝试更改constructor如下:

constructor(props) {
    super(props);

    this.state = {
        address_m: '',
        street: '',
        district: '',
        city: '',
        country: '',
        info: '',
        lat: '',
        lon: '',
    }
    this.goMap = this.goMap.bind(this);

}

您还可以更改goMap为箭头功能并避免绑定this

goMap = () => this.props.navigation.navigate('Map');

并且您必须更改pressAdd函数,因为您在goMap()内部调用setTimeout并且它将在不等待延迟的情况下执行。您需要传递函数而不是调用它。

setTimeout(this.goMap, 800);

推荐阅读