Reactjs React Native-在评估promise时,Undefined不是对象
我是一个初学者,母语程序员。我试图在fetch函数中返回responseJSON。我知道它是异步的,将返回承诺,因此我需要使用.then(),但当它说undefined不是对象时 这是密码 auth.jsReactjs React Native-在评估promise时,Undefined不是对象,reactjs,react-native,Reactjs,React Native,我是一个初学者,母语程序员。我试图在fetch函数中返回responseJSON。我知道它是异步的,将返回承诺,因此我需要使用.then(),但当它说undefined不是对象时 这是密码 auth.js export const onVerify = (email,password,navigation) => { console.log('Verifying'); fetch('xxx', {
export const onVerify = (email,password,navigation) => {
console.log('Verifying');
fetch('xxx',
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'email=' + email + '&password=' + password
})
.then((response) => response.json())
.then((responseJson) => {
if(responseJson.status == '200') {
Alert.alert(
'Login Successful',
'Welcome Home'
);
let data = {
name: responseJson.name,
id : responseJson.id
};
onSignIn();
return responseJson
}
在我的签名中
export default class SignIn extends React.Component{
step(){
onVerify(this.state.email,this.state.password,this.props.navigation).then(
function(data) {
console.log(data);
}
);
}
正如@teivaz在评论中所说,您的
onVerify
函数不返回任何内容。因为fetch
调用是异步的。因此,您可以从onVerify
返回一个Promise
,然后您就可以从step
函数中解析它
export default class SignIn extends React.Component{
step(){
onVerify(this.state.email,this.state.password,this.props.navigation).then(
function(data) {
console.log(data);
}
)
.catch(err => console.log('Error occured', err));
}
}
这就是你可以实现的方式
export const onVerify = (email,password,navigation) => {
return new Promise((resolve, reject) => {
fetch('endpoint',
{
method,
headers,
body,
})
.then((response) => response.json())
.then((responseJson) => {
if(responseJson.status == '200') {
Alert.alert(
'Login Successful',
'Welcome Home'
);
let data = {
name: responseJson.name,
id : responseJson.id
};
onSignIn();
resolve(responseJson)
}
})
.catch(err => reject(err));
}
}
此外,确保捕获步骤
功能中的错误(如果有)
export default class SignIn extends React.Component{
step(){
onVerify(this.state.email,this.state.password,this.props.navigation).then(
function(data) {
console.log(data);
}
)
.catch(err => console.log('Error occured', err));
}
}
函数“onVerify”似乎没有返回任何内容。它应该返回responseJson,对吗@泰瓦兹