我可以在this
函数中访问正确的signInWithEmail
上下文,但是axios的回调函数中的this
上下文是undefined
。我可以使用SignInUser
调用组件渲染内的用户操作this.props.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);
答案 0 :(得分:0)
您可以在=>
回调中使用箭头功能(then
)。在箭头功能内,Context
(此)不会自动更改。试试这个:
API.post('/token/', {
username: username,
password: pass
}).then(response => {
console.log(response.data);
console.log(this.props);
}).catch(error => {
console.log(error);
});
N.B。在Simple函数内部(您用作.then()回调)Context
(此)将是全局/窗口!
答案 1 :(得分:0)
使用箭头功能保留反应组件的上下文
}).then((response) => {
console.log(response.data);
console.log(this.props); // undefined here
})....