问题
I'm trying to get an item from async storage.
componentDidMount() {
console.log('componentDidMount')
AsyncStorage.getItem(STORAGE_KEY)
.then(storage => console.log('then', storage))
.catch(err => console.log('catch', err))
}
Also trying this way:
componentDidMount() {
console.log('componentDidMount')
AsyncStorage.getItem(STORAGE_KEY, (err, data) => {
console.log('data', data);
console.log('err', err)
});
}
But no matter how I do it, the debugger is outputting only the componentDidMount
log and I'm not getting results at all.
Any idea what's wrong here?
EDIT: I'm running the app through expo
回答1:
There was a problem with expo. After restarting expo completely the same code I originally posted worked fine.
回答2:
You should try this:
async componentDidMount(){
await AsyncStorage.getItem(STORAGE_KEY)
.then( (value) =>{
console.warn(value);
}
);
}
Hope it works.
回答3:
I had that problem with android, and I could only solve it bundling.
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
.
I added this command in the scripts in package.json.
回答4:
AsyncStorage is an asynchronous function. It means that id you 'd like to use it in a function, it have to be asynchronous. The way to make it asynchronous is putting async keyword before the name of the function.
async componentDidMount() {
console.log('componentDidMount')
AsyncStorage.getItem(STORAGE_KEY)
.then(storage => console.log('then', storage))
.catch(err => console.log('catch', err))
}
This is how it should be. Greetings
来源:https://stackoverflow.com/questions/48251830/asyncstorage-not-resolving-or-rejecting