我正在尝试在React Native中进行API调用以处理用户身份验证。我将this.state.email
和 this.state.password
(两者都绑定到文本输入框)传递给我services/
文件夹中的一个函数,该函数执行调用。之后,屏幕应导航到主页堆栈或返回错误。这是我的登录界面代码:
import AuthService from ...
export default class LoginScreen extends Component {
constructor(props) {
super(props);
this.login = this.login.bind(this);
this.state = {
email: '',
password: '',
};
}
login() {
AuthService.login(this.state.email, this.state.password)
.then(this.props.navigation.navigate('Main')) //Move to home screen
.catch(console.error('Error')); //Handle error
}
render() {
return (
<View>
<TextInput
onChangeText={email => this.setState({ email })}
value={this.state.email}
/>
<TextInput
onChangeText={password => this.setState({ password })}
value={this.state.password}
/>
<TouchableOpacity onPress={this.login}>
<Text style={styles.text}>Submit</Text>
</TouchableOpacity>
</View>
);
}
}
这是我的AuthService函数:
login(email, password) {
// Check if credentials exist
if (!email || !password) {
return undefined;
}
return fetch(
`${AUTH_ROOT}/login`,
{
method: 'POST',
body: { email, password },
}
.then(
res => {
const data = { ...res.data };
if (!data) {
throw new Error('No user returned from auth service');
}
},
res => {
context.error = 'Could not login';
console.log(res);
}
)
);
},
但是我遇到了错误:
> undefined is not a function (near '...{
> method: 'POST',
> body: {
> email: email,
> password: password,
> } }.then...')
这是什么意思?我的电话没有正确完成吗?