我能够在 signInWithEmail
函数中访问正确的 this
上下文,但是 axios 回调函数中的 this
上下文是未定义
。我可以使用 this.props.signInUser
在组件渲染中调用用户操作 SignInUser
。但我想根据 api 响应来调用它。
这是我的组件中的代码
import React, { Component } from 'react';
import { View, Text, StyleSheet, Button, TextInput } from 'react-native';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { signInUser } from "../actions/UserActions"
import API from "../api/config";
class LoginForm extends Component {
constructor(props) {
super(props);
console.log(props)
this.state = { username: '', password: '' };
this.signInWithEmail = this.signInWithEmail.bind(this);
}
signInWithEmail(username, pass) {
console.log(this.props); // correct context here
API.post('/token/', {
username: username,
password: pass
}).then(function (response) {
console.log(response.data);
console.log(this.props); // undefined here
}).catch(function (error) {
// Show error or redirect
console.log(error);
});
}
render() {
return (
<View>
<Text>access: {this.props.userState.accessToken}</Text>
<Text>refres: {this.props.userState.isSignout.toString()}</Text>
<Text>username: {this.state.username}</Text>
<Text>password: {this.state.password}</Text>
<Text style={styles.inputLabel}> Username </Text>
<TextInput
style={styles.input}
autoCapitalize="none"
onChangeText={(username) => this.setState({ username })}
value={this.state.username}
/>
<Text style={styles.inputLabel}> Password </Text>
<TextInput
style={styles.input}
secureTextEntry
onChangeText={(password) => this.setState({ password })}
value={this.state.password}
/>
<Button title="Sign in with email" onPress={() => this.signInWithEmail(this.state.username, this.state.password)} />
{/* <Button title="Sign in with email" onPress={() => this.props.signInUser("dummy-token", "dummy-refresh")} /> */}
</View>
);
}
};
const styles = StyleSheet.create({
label: {
fontSize: 16,
fontWeight: 'normal',
marginBottom: 48,
borderColor: "#FFF222"
},
divider: {
borderBottomColor: '#000000',
borderBottomWidth: 1,
marginVertical: 10,
},
input: {
backgroundColor: '#F0EEEE',
height: 40,
borderRadius: 5,
marginBottom: 10,
fontSize: 18
},
inputLabel: {
fontSize: 18,
fontWeight: "bold"
}
});
const mapStateToProps = (state) => {
const { userState } = state
return { userState }
}
const mapDispatchToProps = dispatch => (
bindActionCreators({
signInUser,
}, dispatch)
);
export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);
最佳答案
您可以在 then
回调中使用箭头函数 (=>
)。在箭头函数内部,Context
(this) 不会自动更改。试试这个:
API.post('/token/', {
username: username,
password: pass
}).then(response => {
console.log(response.data);
console.log(this.props);
}).catch(error => {
console.log(error);
});
注意在 Simple 函数内部(您用作 .then() 回调)Context
(此)将是全局/窗口!
关于javascript - 无法在 axios 回调 React Native 中访问正确的 this 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60794148/