Reactjs 如何在AsyncStrorage函数中设置变量值
我的方法是,当我使用AsyncStorage.getItem('value')从另一个页面获取值时,我希望将变量的值设置为从AsyncStorage函数获取的项。我的代码是:Reactjs 如何在AsyncStrorage函数中设置变量值,reactjs,react-native,Reactjs,React Native,我的方法是,当我使用AsyncStorage.getItem('value')从另一个页面获取值时,我希望将变量的值设置为从AsyncStorage函数获取的项。我的代码是: import React, { Component } from "react"; import { AsyncStorage } from "react-native"; export default class B extends Component { static message=()=>{
import React, { Component } from "react";
import { AsyncStorage } from "react-native";
export default class B extends Component {
static message=()=>{
AsyncStorage.getItem('value').then((value) => {
console.log(value) // i have got value in console but i dont know how to set it to variable
});
}
}
现在,您可以使用message获取值假设您有一个名为storeasynda的变量
import React, { Component } from "react";
import AsyncStorage from '@react-native-community/async-storage'; // please change this as asyncstorage as other has been deprecated read the docs once
export default class B extends Component {
constructor(props){
this.state={
storeAsynData:''
}
}
static message=()=>{
AsyncStorage.getItem('value').then((value) => {
console.log(value) // i have got value in console but i dont know how to set it to variable
this.setState({storeAsynData:value});
});
}
}
希望它能帮助您使用以下功能:
import AsyncStorage from '@react-native-community/async-storage'
export const LOCAL_STORAGE_LABLES = { TOKEN: "TOKEN" }
class LocalStorage {
static storeToken = async token => {
await AsyncStorage.setItem(LOCAL_STORAGE_LABLES.TOKEN, token);
};
static getToken = async () => {
return await AsyncStorage.getItem(LOCAL_STORAGE_LABLES.TOKEN);
};
static clearToken = async () => {
return await AsyncStorage.removeItem(LOCAL_STORAGE_LABLES.TOKEN);
};
}
export { LocalStorage };
无论你想在哪里使用,都可以打电话:
import AsyncStorage from '@react-native-community/async-storage'
export const LOCAL_STORAGE_LABLES = { TOKEN: "TOKEN" }
class LocalStorage {
static storeToken = async token => {
await AsyncStorage.setItem(LOCAL_STORAGE_LABLES.TOKEN, token);
};
static getToken = async () => {
return await AsyncStorage.getItem(LOCAL_STORAGE_LABLES.TOKEN);
};
static clearToken = async () => {
return await AsyncStorage.removeItem(LOCAL_STORAGE_LABLES.TOKEN);
};
}
export { LocalStorage };
存储令牌
LocalStorage.storeToken(token),
领取代币
const _bootstrapAsync = async () => {
const userToken = await LocalStorage.getToken();
}
useEffect(() => {
_bootstrapAsync();
});
注意:必须使用async and await函数调用,因为它的返回承诺您想在哪里设置新值?@vikrantnegi007,函数内的任何地方它都会抛出一个错误,说“B.setState不是函数”