![](/img/trans.png)
[英]How to pass a variable from a Request as the return value of the global function js
[英]how to pass function variable by return function() in js
我曾与本机反应,我有一个问题......
const SignIn = () => {
screensplash()
fetch('http://api.megamouj.ir/api/v1/logincheck/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: username,
password: password
})
})
.then((response) => response.json())
.then((responseJson) => {
login(responseJson.token).then(
(token) => {
setToken(token)
getMoviesFromApiAsync()
}
)
})
}
当程序继续时
login(responseJson.token)
我遇到了这个错误:
Possible Unhandled Promise Rejection (id: 0): TypeError: Cannot read property 'then' of undefined
这是我的login()
函数:
const login = (token) => {
setLoading(true)
AsyncStorage.setItem('token', token, (error) => {
if (token == 'wrong') {
setIsLoggedIn(false)
setLoading(false)
ToastAndroid.show(
'error',
ToastAndroid.SHORT
)
} else if (!error) {
setIsLoggedIn(true)
setLoading(false)
}
})
return token }
请帮帮我!
您可以使用async
/ await
处理从AsyncStorage.setItem
返回的承诺并返回包含token
的承诺:
const login = async (token) => {
setLoading(true)
await AsyncStorage.setItem('token', token, (error) => {
if (token == 'wrong') {
setIsLoggedIn(false)
setLoading(false)
ToastAndroid.show(
'error',
ToastAndroid.SHORT
)
} else if (!error) {
setIsLoggedIn(true)
setLoading(false)
}
})
return token
}
似乎您甚至没有修改token
。 退货没有意义。 您可以使用responseJson.token
代替:
const SignIn = () => {
screensplash()
fetch('http://api.megamouj.ir/api/v1/logincheck/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: username,
password: password
})
})
.then((response) => response.json())
.then((responseJson) => login(responseJson.token))
.then(() => {
setToken(responseJson.token)
getMoviesFromApiAsync()
})
}
和
const login = async (token) => {
setLoading(true)
await AsyncStorage.setItem('token', token, (error) => {
if (token == 'wrong') {
setIsLoggedIn(false)
setLoading(false)
ToastAndroid.show(
'error',
ToastAndroid.SHORT
)
} else if (!error) {
setIsLoggedIn(true)
setLoading(false)
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.