[英]setState not working inside AsyncStorage in react native?
setState在React Native的AsyncStorage內部不起作用
constructor(props) {
super(props);
this.state = {userId: ''};
}
componentDidMount() {
AsyncStorage.getItem('USER_ID', (err, result) => {
if (!err && result != null) {
this.setState({
userId: result
});
}
else {
this.setState({
userId: null
});
}
});
alert(this.state.userId);
let userId = this.state.userId;
fetch('http://localhost/JsonApi/myprofile.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
userId: userId,
}),
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({userDetails: responseJson});
})
.catch((error) => {
console.error(error);
});
}
使用setState
和alert設置userId
值根本不返回任何值。 嘗試了Stackoverflow的其他解決方案,但未達到我的預期。
注意:代碼已更新。 從AsyncStorage獲取userId后,它將傳遞給fetch。 此處,缺少userId值。
有兩種方法可以做到這一點。 一種是簡單的,而另一種是根據反應建議的正確方法
一個是傳遞值直接聲明。
.then((responseJson) => {
// this.setState({userDetails: responseJson});
this.state.userDetails=responseJson;
this.setState({}); //for update render
})
第二條路在這里
在渲染功能中檢查狀態值,例如:如果UserDetails狀態為null,則只要userDetails狀態獲取數據再次執行並提供完美結果,都不會給您錯誤。
render() {
return (
<div>
{this.state.userDetails ?
this.state.userDetails.map((data, index) =>
<tr key={index}>
<td>{data.userName}</td>
<td>{data.userEmail}</td>
</tr>
)
: null
}
</div>)}
讓我知道收益。 如果面臨問題
更新狀態后嘗試發出警報。 狀態更新后,您將獲得回調。
this.setState({
userId: result
},function(){
console.log("userId in async = ", this.state.userId);
alert(this.state.userId);
});
我不知道你為什么寫那么多代碼。
AsyncStorage.getItem("USER_ID").then((value) => {
console.log("userId in async = " + value);
this.setState({
userId: value
});
});
error
和result
,因為如果該參數為null,則將狀態下的userId設置為null。 因此您可以直接將value
設置為狀態userId
。 也可以有不同的方式,例如使用async
方法。
const getUserId = async () => {
try {
const userId = await AsyncStorage.getItem('USER_ID') || 'none';
} catch (error) {
// Error retrieving data
console.log(error.message);
}
return userId;
}
你可以使用
this.setState ({
userId : getUserId()
});
我不喜歡這種方式,因為我需要使用async
& await
關鍵字創建另一個方法。
更新
您的工作與getIten();
userId有關getIten();
,因為您在調用AsyncStorage
之后立即提醒userId。 並且AsyncStorage
在您調用alert
之后返回值。
AsyncStorage.getItem("USER_ID").then((value) => {
console.log("userId in async = " + value);
this.setState({
userId: value
});
alert(this.state.userId); // move this line here
});
// removed from here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.