无法读取.then()=> {}中未定义的属性“ navigate”

时间:2019-10-01 21:53:11

标签: javascript reactjs react-native react-navigation

为什么我无法在以下代码中导航至屏幕“ App”。我收到错误消息:

  

无法读取未定义的属性“ navigate”

  async signIn() {
    const { username, password } = this.state
    await Auth.signIn(username, password)
    .then(user => {
      this.setState({ user })
      this.props.navigation.navigate("App");
      Alert.alert('Signed In Successful!')
    })
    .catch(err => {
        console.log('Error when signing in: ', err)
        Alert.alert('Error when signing in: ', err)
    })
  }
}

1 个答案:

答案 0 :(得分:1)

您正在兑现承诺并等待。您要么等待登录,要么删除异步/等待并将其视为承诺。另外,可能是您尚未绑定函数,因此“ this”指向未定义。

要么:

async signIn = () => {
    const { username, password } = this.state
    let user = await Auth.signIn(username, password);
     this.setState({ user })
      this.props.navigation.navigate("App");
      Alert.alert('Signed In Successful!')

  }
}

signIn = () => {
    const { username, password } = this.state
    Auth.signIn(username, password)
    .then(user => {
      this.setState({ user })
      this.props.navigation.navigate("App");
      Alert.alert('Signed In Successful!')
    })
    .catch(err => {
        console.log('Error when signing in: ', err)
        Alert.alert('Error when signing in: ', err)
    })
  }
}