从 Promise 回调中导航

Sam*_*one 1 javascript react-native react-navigation

我刚刚开始使用 React Native,在尝试从 Promise 回调中导航时遇到了以下问题。

这是我尝试运行的以下代码。如果 http 请求返回用户的登录信息正确,我想导航到另一个屏幕。

login() {
  axios({
      method: 'post',
      url: `${Globals.WebAPI}/api/authentication/login`,
      data: {
        username: this.state.username,
        password: this.state.password
      }
  })
  .then(function(response) { 
      console.log(response.data.token)
      AsyncStorage.setItem("AuthToken", response.data.token);
      this.props.navigation.navigate('PictureDetails', {base64: photo.base64});
  })
  .catch(function(error) {
      console.log(error);
  });
}



render() {
return (
  <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
    <Text>Home Screen</Text>
    <Button
      title="Go to Details"
      onPress={this.goToDetails}
    />
    <Button
      title="Signup"
      onPress={this.goToSignup}
    />
    <Text>Username</Text>
    <TextInput
    style={{height: 40, width: 200, borderColor: 'gray', borderWidth: 1}}
    onChangeText={(text) => this.setState({username: text})}
    value={this.state.username}
  />
  <Text>Password</Text>
  <TextInput
    style={{height: 40, width: 200, borderColor: 'gray', borderWidth: 1}}
    onChangeText={(text) => this.setState({password: text})}
    value={this.state.password}
  />
  <Button
      title="Login"
      onPress={this.login}
    />
  </View>
)};
Run Code Online (Sandbox Code Playgroud)

这是我从这个函数中得到的错误:

undefined is not an object (evaluating 'this.props.navigation')
Run Code Online (Sandbox Code Playgroud)

我觉得这个错误是因为我没有完全理解 props 的用法,所以我希望这个答案有助于巩固我对 React Native 中发生的事情的了解。

提前致谢

Kar*_*yan 5

这部分失去this约束力:

  .then(function(response) { 
      console.log(response.data.token)
      AsyncStorage.setItem("AuthToken", response.data.token);
      this.props.navigation.navigate('PictureDetails', {base64: photo.base64});
  })
Run Code Online (Sandbox Code Playgroud)

所以当你打电话时this.props.navigation.navigate(thisundefined,这就是你的错误告诉你的。

最简单的解决方法是将常规函数转换为箭头函数,该函数在词法上将 绑定this到周围上下文的this值。

  .then((response) => { 
      console.log(response.data.token)
      AsyncStorage.setItem("AuthToken", response.data.token);
      this.props.navigation.navigate('PictureDetails', {base64: photo.base64});
  })
Run Code Online (Sandbox Code Playgroud)

更多信息请点击此处