Her*_*vic 1 javascript reactjs react-native asyncstorage
我有一个小的 React Native 组件,我尝试通过从本地存储(AsyncStorage)读取值来初始化状态。但是当我从构造函数调用外部方法时,我的状态值 未定义。
这是我的代码的一部分:
constructor(props) {
super(props);
this.state = {
languageChecked: I18n.locale,
anonymityChecked: this.pickLocalKey('anonymity', true),
locationChecked: this.pickLocalKey('location', false),
notificationChecked: this.pickLocalKey('notification', false),
statisticsChecked: this.pickLocalKey('statistics', false),
};
console.log("STATE: " + this.state.anonymityChecked); // UNDEFINED
}
pickLocalKey(key, defaultValue) {
AsyncStorage.getItem(key).then((value) => {
const item = (value !== null && value !== undefined) ? value : defaultValue;
console.log(item);
return item;
});
}
Run Code Online (Sandbox Code Playgroud)
有谁知道如何解决这个问题?先感谢您
您在问题中粘贴的代码存在几个问题。
首先,它 constructor
是同步的,您尝试在其中执行异步任务。这不是一个好主意。
如果您需要从中加载值AsyncStorage
并将它们存储在其中,state
您应该在componentDidMount
因此,在构造函数中设置初始值,添加一个附加值loaded: false
。这在以后会变得很重要。
constructor (props) {
super(props);
this.state = {
languageChecked: I18n.locale,
anonymityChecked: true,
locationChecked: false,
notificationChecked: false,
statisticsChecked: false,
loaded: false // <- add this additional value
};
}
Run Code Online (Sandbox Code Playgroud)
目前您的pickLocalKey
函数实际上没有返回任何内容。返回值被困在一个承诺中。幸运的是,我们可以将函数转换为使用async/await
. 所以它应该看起来像这样:
pickLocalKey = async (key, defaultValue) => {
try {
let value = await AsyncStorage.getItem(key);
const item = (value !== null && value !== undefined) ? value : defaultValue;
return item === 'true'; // this will make sure we get a Boolean back as long as you store strings 'true' and 'false' for your Booleans
} catch (error) {
return defaultValue;
}
}
Run Code Online (Sandbox Code Playgroud)
注意await
可以抛出异常,因此最好将其包装在try/catch
.
然后在你的中componentDidMount
你应该调用来检索值AsyncStorage
async componentDidMount () {
// these won't throw as we are catching the error before it gets here
let anonymityChecked = await this.pickLocalKey('anonymity', true);
let locationChecked = await this.pickLocalKey('location', false);
let notificationChecked = await this.pickLocalKey('notification', false);
let statisticsChecked = await this.pickLocalKey('statistics', false);
// set all items in state in one go as multiple calls to setState are not good
this.setState({
anonymityChecked,
locationChecked,
notificationChecked,
statisticsChecked,
loaded: true . // <- we set loaded to true
}, () => console.log(this.state)); // this is how you check state after it has been set
}
Run Code Online (Sandbox Code Playgroud)
那么render
你现在应该使用这样的事实:loaded
来呈现正确的视图:
render () {
if (this.state.loaded) {
return (
this is the view that you actually want to show
)
} else {
return (
this is the view that you will show when everything is loading
)
}
}
Run Code Online (Sandbox Code Playgroud)
以下是一些值得阅读的文章:
归档时间: |
|
查看次数: |
1991 次 |
最近记录: |