【问题标题】:Async Storage get not updating user interface render jsx异步存储不更新用户界面渲染 jsx
【发布时间】:2019-05-10 17:11:01
【问题描述】:

我对异步存储和原生反应非常陌生。我正在尝试将数据/json异步保存在持久存储中。然后读回来并在 UI 上显示。

以下是我尝试过的:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, FlatList, Image} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';


const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

type Props = {};
export default class App extends Component<Props> {


  getData = async () => {
    try {
      const value =  AsyncStorage.getItem('@storage_Key')
      if(value !== null) {
        // value previously stored
        this.setState({
          datasource: JSON.parse(value)
         })
      }else{
        fetch('https://jsonplaceholder.typicode.com/photos', {
          method: 'GET'
       })
       .then((response) => response.json())
       .then((responseJson) => {
          console.log(responseJson);
          this.setState({
            datasource: responseJson
           })
          try {
             AsyncStorage.setItem('@storage_Key',JSON.stringify(responseJson))
          } catch (e) {
            // saving error
          }

       })
       .catch((error) => {
          console.error(error);
       });
      }
    } catch(e) {
      // error reading value
    }
  }


  constructor(props){
    super(props);
    this.state={
          datasource:'hello world'
    };
}

componentDidMount = () => {

  this.getData.bind(this);

}
render() {
  return (
     <View style = {{
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center'
    }}>
   <FlatList
   data = {this.state.datasource}
   renderItem={({item}) => 
   <View>
   <View style = {{
      flex: 1,
      flexDirection : 'row'
    }}>

<Image
          style={{width: 50, height: 50}}
          source={{uri: item.thumbnailUrl}}
        />
<View>
   <Text> albumId > {item.albumId} </Text> 
   <Text> id > {item.id} </Text>
   <Text> title > {item.title} </Text>
   </View>
    </View>


   <View
  style={{
    borderBottomColor: 'orange',
    borderBottomWidth: 5,
  }}
/>
   </View>
   }
   />
     </View>
  )
}
}

以下是输出: 谢谢!

编辑 1:

getData = async () => {
try {
  const value = await AsyncStorage.getItem('@storage_Key')
  if(value !== null) {
    // value previously stored
    this.setState({
      datasource: JSON.parse(value)
     })
  }else{
    fetch('https://jsonplaceholder.typicode.com/photos', {
      method: 'GET'
   })
   .then((response) => response.json())
   .then((responseJson) => {
      console.log(responseJson);
      this.setState({
        datasource: responseJson
       })
      try {
        await AsyncStorage.setItem('@storage_Key',JSON.stringify(responseJson))
      } catch (e) {
        // saving error
      }

   })
   .catch((error) => {
      console.error(error);
   });
  }
} catch(e) {
  // error reading value
}

}

更新到异步后出现错误:

【问题讨论】:

    标签: react-native react-native-flatlist asyncstorage


    【解决方案1】:

    getItemsetItem 是异步操作...你需要等待它:

      const value =  await AsyncStorage.getItem('@storage_Key')
    

    -

       .then(async (responseJson) => {
          console.log(responseJson);
          this.setState({
            datasource: responseJson
           })
          try {
            await AsyncStorage.setItem('@storage_Key',JSON.stringify(responseJson))
          } catch (e) {
            // saving error
          }
    
       })
    

    【讨论】:

    • 您是否为 setItem 和 getItem 添加了等待?如果是,请尝试控制台记录您的 api 响应 ...
    • 还有一件事 .. . 确保清除您的存储空间... 因为它可能有不正确的值从您之前的试验await AsyncStorage.clear() ...或await AsyncStorage.removeItem('YourKey') 中出来
    • await AsyncStorage.setItem('@storage_Key',JSON.stringify(responseJson)) 它说不能在异步函数之外使用关键字等待:(
    猜你喜欢
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 2017-10-12
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    相关资源
    最近更新 更多