这里我粘贴了为 mobx 状态管理编写的类组件的代码,并将其调用到另一个文件;问题是我有超过 450 个 API 响应,并且需要在本地存储,所以我已经尝试过,但我没有获得任何值,也没有获得数据库中存储的数据。请帮帮我。
class ProductStore {
constructor() {
makeAutoObservable(this);
}
screenWidth = width;
screenHeight = height;
headerHeight = 0;
isiOS = Platform.OS === 'ios';
isAndroid = Platform.OS === 'android';
isProductLoading = 'pending';
productData = [];
filterdData = [];
search = '';
isFlatlistRender = false;
setFields(eName, data) {
this[eName] = data;
console.log(eName, data);
}
getproductData = () => {
if (this.isProductLoading == 'loading') {
return true;
}
this.isProductLoading = 'loading';
this.productData = [];
let headers = new Headers();
headers.set(
'Authorization',
'Basic ' + encode('username:password'),
);
fetch('some_url', {
method: 'GET',
headers: headers,
})
.then(response => response.json())
.then(responseJson => {
console.log('.....', responseJson);
AsyncStorage.setItem(
'ACCESS_TOKEN',
JSON.stringify(responseJson),
err => {
if (err) {
console.log('an error');
throw err;
}
console.log('success');
},
).catch(err => {
console.log('error is: ' + err);
});
try {
const value = AsyncStorage.getItem('ACCESS_TOKEN');
if (value !== null) {
console.log(JSON.parse(value));
}
} catch (error) {}
this.productData = responseJson;
this.isProductLoading = 'done';
})
.catch(error => {
console.error(error);
this.isProductLoading = 'error';
});
};
}
export default new ProductStore();
AsyncStorage.getItem() 返回一个承诺,而不是值。因此,只需在
then
行后面添加一个 AsyncStorage.getItem('ACCESS_TOKEN');
块即可。会是这样的
AsyncStorage.getItem('ACCESS_TOKEN').then(value => {
if (value !== null) {
console.log(JSON.parse(value));
}
}).catch(err => console.error(err));