我正在尝试在componentDidMount中获取数据,设置状态和更改路由,但无法完成(仅在单击屏幕后)。我想有些东西与fetch的异步性质有关但是如何修复?
componentDidMount(){
AsyncStorage.multiGet([USER_TOKEN, USER_REFRESH_TOKEN,USER_REMEMBERED]).then((data) => {
const userRemembered = JSON.parse(data[2][1])
const userAccessToken = data[0][1]
const userRefreshToken = data[1][1]
if (userRemembered) {
fetch("SOME_URL", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
refreshToken: userRefreshToken
})
})
.then(response => response.json())
.then(responseData => {
console.log(responseData); // only after clicking on the screen it is logged
if (responseData.success) {
AsyncStorage.multiSet([[USER_TOKEN,responseData.response.accessToken],[USER_REFRESH_TOKEN,responseData.response.refreshToken],[USER_REMEMBERED,JSON.stringify(true)]])
this.setState({
token:responseData.response.accessToken,
refreshToken: responseData.response.refreshToken,
isLoggedIn: true
}) //only after clicking on the screen state is changed
this.changeRoute(this.state) //only after clicking on the clicking on the screen route is changed
}
else {
console.log("API is not responding");
}
})
.catch((error) => {
console.log(error)
})
}
else{
console.log('user has not checked Remember Me');
}
})
}
答案 0 :(得分:0)
我终于明白了。我打开了远程JS调试,这让事情搞得一团糟。我把它关掉了,一切正常。