我创建了一个文件GetSetStorage
include AsyncStorage
,当我尝试使用它时,我发现它无效。
这是我的GetSetStorage
文件:
import { AsyncStorage } from 'react-native';
class GetSetStorage {
setStorageAsync(key, value) {
console.log('start set storage');
console.log(`key =>${key}`);
console.log(`vaue =>${value}`);
return new Promise((resolve, reject) => {
console.log('Why is no working here ?');
AsyncStorage.setItem(key, value, (error) => {
console.log(error);
if (error) {
console.log('===');
console.log(`set${key}error${error}`);
console.log('===');
reject(`set${key}error${error}`);
} else {
console.log('===');
console.log(`set${key}succeed`);
console.log('===');
resolve(true);
}
});
});
}
getStorageAsync(key) {
return new Promise((resolve, reject) => {
AsyncStorage.getItem(key, (error, result) => {
console.log(error);
console.log('where is my error');
if (error) {
console.log('===');
console.log(`load ${key} error ${error}`);
console.log('===');
reject(`load ${key} erro ${error}`);
} else {
console.log('===');
console.log(`load ${key} succeed`);
console.log('===');
resolve(result);
}
});
});
}
}
export default new GetSetStorage();
我在我的组件中使用它:
import GetSetStorage from '../storage/GetSetStorage';
componentWillMount() {
GetSetStorage.setStorageAsync('testKey', 'test value');
}
我看到我的console.log,我发现setItem
无效。为什么?
任何帮助将不胜感激。提前谢谢。
答案 0 :(得分:2)
Asyncstorage还会返回一个promise,因此您可以执行类似
的操作AsyncStorage.setItem('email', JSON.stringify(this.state.UserEmail))
.then(() => console.log('saved email successfully'))
.catch(err => console.error('something went wrong', err));
同样,要获取相同的密钥,您可以执行以下操作:
AsyncStorage.getItem('email')
.then(val => {
if (val !== null) console.log(val); // You can do whatever you want with the email
})
.catch(err => console.error(err)) // if there was an error fetching data
请注意,如果异步存储中没有任何内容,则会返回' null'所以为了处理错误,你需要将它们放在if语句而不是catch
中答案 1 :(得分:1)
//检查出来!
return Stream.of((int)levenshteinScore, reverseComparison, regionStart, regionLength).map(Match::new);
public static class Match{
// Properties
public int levenshteinSimilarity;
public boolean reverseComparison;
public int regionStart;
public int regionLength;
// Constructor
public Match(int levenshteinSimilarity, boolean reverseComparison, int regionStart, int regionLength){
this.levenshteinSimilarity = levenshteinSimilarity;
this.reverseComparison = reverseComparison;
this.regionStart = regionStart;
this.regionLength = regionLength;
}
}