【问题标题】:trying to save to save data in asycstorage but unable to it so试图保存以将数据保存在 asycStorage 中,但无法保存
【发布时间】: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


    【解决方案1】:

    如果你想使用 mobx,我猜有中间件可以将状态保存在 localStorage 中,比如 redux 上的 Redux-Persist

    但如果您只想使用 AsyncStorage,那么您可以这样做。

    保存的已经正确了。

    这个是get

    //save this code on helper or something
    export const getItem = async ()=>{
       try{
           const data = await AsyncStorage.getItem('dataKey');
           if(!data) throw new Error("Data doesn't exist yet")
           return [true,JSON.parse(data)];
           //first array is boolean to check if it success or not
           //2nd array is data or error message (if false)
        } catch (e){
           return [false,e.message];
        }   
    }
    

    然后你在 didmount 或 useEffect 中调用它并保存到 state

    import {getItem} from './FileLocation';
    
    //for class component
    async ComponentDidMount(){
       const [success,data] = await getItem();
       if(success){
          this.setState({data})
       } else{
          Alert.alert('Error',data)
       }
    }
    
    //functional
    
    const [data,setData] = React.useState([]);
    
    const FetchItem = async ()=>{
       const [success,data] = await getItem();
        if(success){
          setData(data)
       } else{
          Alert.alert('Error',data)
       }
    }
    
    React.useEffect(()=>{
       FetchItem();
    },[])
    
    

    【讨论】:

      猜你喜欢
      • 2018-01-24
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 2013-06-11
      相关资源
      最近更新 更多