【发布时间】:2022-01-11 09:10:15
【问题描述】:
这里我已经粘贴了我的整个代码,这里我有一个有 400 多个响应的 api,它需要存储在 asyncstorage 中,就像它需要存储在本地数据库中一样,这个 api 是有限的,人们还建议我异步编写这个等待,但我不知道异步等待您可以编辑代码并帮助我吗?重要的是我正在使用 mobx 状态树来访问另一个文件中的此代码。提前致谢。
import {makeAutoObservable, action} from 'mobx';
import {Dimensions, Platform} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
const {width, height} = Dimensions.get('window');
import {encode} from 'base-64';
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);
}
// searchFilter = text => {
// if (text) {
// // setIsfilterdData(ProductStore.productData);
// const fData = this.productData;
// const newData = fData.filter(item => {
// const itemData =
// item.product || item.id
// ? item.product.toUpperCase() || item.id
// : ''.toUpperCase();
// const textData = text.toUpperCase();
// return itemData.indexOf(textData) > -1;
// });
// this.filterdData = newData;
// this.search = text;
// } else {
// this.isFlatlistRender = true;
// this.search = text;
// }
// };
getproductData = async () => {
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('dataKey', JSON.stringify(responseJson));
// retrieving data whenever you need from local storage
AsyncStorage.getItem('dataKey')
.then(responseJson => {
if (responseJson) {
let ourData = JSON.parse(responseJson);
console.log('ourData >>>>> ', ourData);
this.productData = ourData;
this.isProductLoading = 'done';
}
})
.catch(err => console.log('error >>>>> ', err));
// this.productData = ourData;
// this.isProductLoading = 'done';
})
.catch(error => {
console.error(error);
this.isProductLoading = 'error';
});
};
}
export default new ProductStore();
【问题讨论】:
标签: javascript reactjs react-native async-await asyncstorage