我对React Native非常陌生。我正在登录用户。这是我要去的tutorial。我不得不使用XMLHttpRequest而不是fetch,因为我无法使其正确传递POST参数。它发布的PHP页面只是在返回之前回显了userID。它没有返回json字符串或任何东西。
我正在登录用户并使用
this.setState({ userID: request.responseText });
跟踪用户ID。这行代码给我带来了Invariant Violation错误,它期望一个字符串,而我给它一个对象。
App.js(如果您看到任何明显的答案,我会添加注释掉的提取内容
import React, { Component } from 'react'
import { View, Text, Alert, Button, TextInput, TouchableOpacity } from 'react-native';
import Home from './Home';
export default class App extends Component{
state = {
email: '',
pwd: '',
auth_token: '',
userID: ''
}
Login = async () => {
var request = new XMLHttpRequest();
var params = "email=" + this.state.email + "&pwd=" + this.state.pwd;
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
Alert.alert(request.responseText); //this is returning the correct value
if(request.responseText != "ERROR"){
this.setState({ userID: request.responseText });
Alert.alert("Welcome", " You have succesfully logged in");//also returning
}else{
Alert.alert("Oh, no!", " There was a problem");
}
} else {
console.warn('error');
}
};
request.open('POST', 'https://mysitexzy.com/wLoginCE');
request.send(params);
/*
fetch('https://mysitexzy.com/wLoginCE', {
method: 'post',
headers: {
Accept: 'application/json',
// 'Content-Type': 'application/json',
},
body: JSON.stringify({
// "provider": "username",
"email": this.state.email,
"pwd": this.state.pwd
})
}).then((response) => response.json())
.then((res) => {
if(typeof(res.message) != "undefined"){
Alert.alert("Error", "Error: "+ res.message);
}
else{
this.setState({ userID: response });
Alert.alert("Welcome", " You have succesfully logged in");
}
}).catch((error) => {
console.error(error);
});
*/
}
render(){
//If auth token is not present
if(this.state.userID==''){
return(
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'stretch',
}}>
<TextInput
placeholder="Enter User name"
onChangeText={ TextInputValue =>
this.setState({email : TextInputValue }) }
underlineColorAndroid='transparent'
style={
{
textAlign: 'center',
width: '90%',
marginBottom: 7,
height: 40,
borderRadius: 5 ,
fontSize: 20,
}
}
/>
<TextInput
placeholder="Enter password"
onChangeText={ TextInputValue =>
this.setState({pwd: TextInputValue }) }
underlineColorAndroid='transparent'
secureTextEntry={true}
style={
{
textAlign: 'center',
width: '90%',
marginBottom: 7,
height: 40,
borderRadius: 5 ,
fontSize: 20,
}
}
/>
<TouchableOpacity onPress={this.Login.bind(this)}>
<View style={{height: 50, backgroundColor:
'#cc0066',justifyContent: 'center',
alignItems: 'center',}}>
<Text style={{
fontSize: 20,
color: '#FFFFFF',
}}>
Login </Text>
</View>
</TouchableOpacity>
</View>
);
}
/* Checking if the auth token is not empty directly sending the user to Home screen */
else{
return(
<Home />
);
}
}
}
根据教程中的说明,Home.js为空白。