我正在尝试在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...')
这是什么意思?我的电话打不正确吗?
答案 0 :(得分:1)
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);
}
)
},
fetch
的正确语法是
fetch(url, params).then()
相反,您拥有
fetch(url, params.then())