我在 React Native 中有以下課程。可以看出,我有一些定義的“狀態”變數和一個“componentDidMount”呼叫,旨在使用“AsyncStorage”工具檢索以前存盤的變數。
export default class Cast extends Component {
state = {
admin: false,
isPublishing: false,
userComment: "",
hasPermission: false,
paused: true,
_email: false,
_name: false,
_pword: false,
};
getKey = async() => {
try {
var value = await AsyncStorage.getItem('email');
console.log("value variable AFTER getKey: " value);
this.setState({ _email: value });
} catch (error) {
console.log("Error retrieving data" error);
}
}
componentDidMount(){
this.getKey();
}
onPressBtn = () => {
console.log("EMAIL value variable AFTER getKey: " this.state._email) //this should show the value AFTER the retrieval from storage...correct?
};
//...
'AsyncStorage.getItem' 之后的 console.log 陳述句成功地將變數“value”顯示為從存盤中檢索到的(例如“[email protected]”)。但是,我對如何分配此變數并顯示它感到非常困惑。“this.setState({ _email: value });” 要么不起作用,要么我使用不正確的語法來顯示“_email”變數的值。我嘗試了以下方法:
console.log("_email variable AFTER getKey: " _email);
console.log("_email variable AFTER getKey: " this._email);
console.log("_email variable AFTER getKey: " {_email});
console.log("_email variable AFTER getKey: " this.state._email);
以上都沒有正確回傳“_email”變數的值。我在這里做錯了什么?'setState' 分配不正確...?我只是想檢索存盤中的任何值(作為“值”),然后將它們分配給“狀態”中定義的適當變數。非常感謝任何建議。我提前謝謝你。
uj5u.com熱心網友回復:
這取決于when您是否嘗試訪問狀態變數。如果您執行了以下操作:
getKey = async() => {
try {
var value = await AsyncStorage.getItem('email');
console.log("value variable AFTER getKey: " value);
this.setState({ _email: value });
console.log(this.state._email)
} catch (error) {
console.log("Error retrieving data" error);
}
}
然后,這將列印false,這是您所在州的默認設定。設定狀態將導致重新渲染。新值將在之后可用。
考慮以下代碼段。
getKey = async () => {
try {
var value = "test"
console.log("value variable AFTER getKey: " value)
this.setState({ _email: value })
} catch (error) {
console.log("Error retrieving data" error)
}
}
...
render() {
console.log("HELLO VALUE", this.state._email)
return <></>
}
我們會注意到以下輸出列印到控制臺。
LOG HELLO VALUE false
LOG value variable AFTER getKey: test
LOG HELLO VALUE test
uj5u.com熱心網友回復:
您需要在建構式中宣告您的狀態物件
constructor(props) {
super(props);
this.state = {
admin: false,
isPublishing: false,
userComment: "",
hasPermission: false,
paused: true,
_email: false,
_name: false,
_pword: false,
};
//Other codes
}
同樣,當提到一個狀態時,你想使用:例如。您正在嘗試獲取存盤在狀態中的電子郵件
this.state._email
//setting states
this.setState({_email: "newEmail"})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/437209.html
上一篇:Spark入門必知知識點
