为什么我的导航在本机反应中不起作用?

时间:2019-12-14 16:47:09

标签: reactjs react-native

我有在响应本机中运行导航的代码,不幸的是它不起作用。这是我的代码:

_postData() {
    if(this.state.email !== '' || this.state.password !== ''){
      const dataAkun = {
        email: this.state.email,
        password: this.state.password
      }
      const paramsData = new URLSearchParams();
      paramsData.append('email', this.state.email);
      paramsData.append('password', this.state.password);
      //AsyncStorage.setItem('akun', JSON.stringify(dataAkun));
      axios.post('http://radarugi.com/rekber/login.php', paramsData)
        .then(function (response) {
          const resultArray = JSON.stringify(response);
          const kitaParse = JSON.parse(resultArray);
          if(kitaParse.data.statusCode == '1'){
            Alert.alert('Berhasil login!');
            AsyncStorage.setItem('akun', kitaParse.data.keyResult);
            _updateData('akun', kitaParse.data.keyResult);
            this.props.navigation.navigate('HomeWelcome', {akun: kitaParse.data.keyResult});
          }else{
            Alert.alert('Email/Password salah!');
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    }else{
      Alert.alert('Mohon isi email dan password!');
    }
  }

运行该功能时,仅发出“ Berhasil登录!”警报,即使下面有一个命令可以移动到另一个屏幕。

Alert.alert('Berhasil login!');
AsyncStorage.setItem('akun', kitaParse.data.keyResult);
_updateData('akun', kitaParse.data.keyResult);
this.props.navigation.navigate('HomeWelcome', {akun: kitaParse.data.keyResult});

这是我的stackNavigator代码:

const RootStack = createStackNavigator(
  {
    Welcome: LoginWelcome,
    RegisterWelcome: RegisterWelcome,
    HomeWelcome: Home,
  },
  {
    initialRouteName: 'Welcome',
    headerMode: 'none',
  }
);

const AppContainer = createAppContainer(RootStack);

1 个答案:

答案 0 :(得分:0)

有两种方法可以解决此问题。

  1. 将其分配给回调函数,然后在回调函数中使用
_postData() {
    ...
    const that = this;
    axios.post('http://radarugi.com/rekber/login.php', paramsData)
        .then(function (response) {
            ...
            that.props.navigation.navigate('HomeWelcome', {akun: kitaParse.data.keyResult});
            ...
        })
    ...
}
  1. 使用箭头函数作为回调
_postData() {
    ...
    axios.post('http://radarugi.com/rekber/login.php', paramsData)
        .then((response) => {
            ...
            this.props.navigation.navigate('HomeWelcome', {akun: kitaParse.data.keyResult});
            ...
        })
    ...
}