【问题标题】:How to cache data and fetch in reactnative?如何缓存数据并在本机反应中获取?
【发布时间】:2025-11-27 05:20:03
【问题描述】:

我是 Reactnative 和 Javascript 的新手,我正在尝试从 APi 缓存数据并获取它。但它不起作用。我无法呈现数据。我收到错误消息。没有internent时如何缓存和检索缓存中的数据?我已经实现了缓存的代码如下:

export default class ViewpagerP extends Component {
constructor(props) {
    super(props);
    this.state = { isLoading: true, data: [] }
}
async componentDidMount() {
    const photoStorage = await AsyncStorage.getItem('GalleryPhotos')
            console.log(photoStorage);
    if(!photoStorage) {
      try {
        console.log("Null inside")
        const photoResp = await axios.get('https://rallycoding.herokuapp.com/api/music_albums')
        console.log(photoResp)
        const photoData = await JSON.stringify(photoResp.data);
        this.setState({data:photoResp,isLoading:false})
        await AsyncStorage.setItem('GalleryPhotos', photoData);
      } catch(e) {
        console.warn("fetch Error: ", error)
     }
   then(response => this.setState({ data: response.data,isLoading:false }))
   }else{
       this.getPhotos;
   }
 }
 getPhotos = async()=> {
    try {
        data = JSON.parse(await AsyncStorage.getItem('GalleryPhotos'));
        this.setState({data:data,isLoading:false})
        console.log(data);
    }
    catch (error) {
      console.error(error);
    }
  }

render() {

    if (this.state.isLoading) {
        return (
            <View style={{ flex: 1, padding: 20 }}>
                <ActivityIndicator />
            </View>
        )
    }

    console.log(this.state.data);

    return (
        <View style={styles.container}>
            <ImageSlider style={styles.viewPagerStyle}
                loopBothSides
                autoPlayWithInterval={6000}
                images={this.state.data}
                customSlide={({ index, item, style, width }) => (
                    <View key={index} style={[style, styles.customSlideStyle]}>
                        <View style={styles.contentContainer}>
                            <Image source={{ uri: item.image }} style={styles.customImage} />
                            <View style={styles.textContainerStyle}>
                                <Text style={styles.textStyle}>{item.title}</Text>
                            </View>
                        </View>
                    </View>
                )
                }

            />

        </View>
    );
}
}

【问题讨论】:

  • 你为什么有then(response =&gt; this.setState({ data: response.data,isLoading:false }))
  • 这样我就可以存储响应数据
  • 如果我没有错,你不必使用item.image。设置&lt;Image source={{ uri: item }} style={styles.customImage} /&gt; 可以吗?因为该项目包含您在 images 道具中传递的所有内容
  • console.log(this.state.data) 打印什么?
  • 不使用 item.image 怎么获取图片标签?

标签: react-native caching


【解决方案1】:

您需要对代码进行一些更正

  this.getPhotos;

this.getPhotos();

您还可以使用

来检查 internate 是否打开
import { NetInfo} from 'react-native';

查看以下文章,它会对您有所帮助 enter link description here

这里是修正

 export default class ViewpagerP extends Component {
constructor(props) {
    super(props);
    this.state = { isLoading: true, data: [] }
}
async componentDidMount() {
    const photoStorage = await AsyncStorage.getItem('GalleryPhotos')
            console.log(photoStorage);
    if(!photoStorage) {
      try {
        console.log("Null inside")
        const photoResp = await axios.get('https://rallycoding.herokuapp.com/api/music_albums')
        console.log(photoResp)
        const photoData = await JSON.stringify(photoResp.data);
        this.setState({data:photoResp,isLoading:false})
        await AsyncStorage.setItem('GalleryPhotos', photoData);
      } catch(e) {
        console.warn("fetch Error: ", error)
     }
   }else{
       this.getPhotos();
   }
 }
 getPhotos = async()=> {
    try {
        data = JSON.parse(await AsyncStorage.getItem('GalleryPhotos'));
        this.setState({data:data,isLoading:false})
        console.log(data);
    }
    catch (error) {
      console.error(error);
    }
  }

render() {

    if (this.state.isLoading) {
        return (
            <View style={{ flex: 1, padding: 20 }}>
                <ActivityIndicator />
            </View>
        )
    }

    console.log(this.state.data);

    return (
        <View style={styles.container}>
            <ImageSlider style={styles.viewPagerStyle}
                loopBothSides
                autoPlayWithInterval={6000}
                images={this.state.data}
                customSlide={({ index, item, style, width }) => (
                    <View key={index} style={[style, styles.customSlideStyle]}>
                        <View style={styles.contentContainer}>
                            <Image source={{ uri: item.image }} style={styles.customImage} />
                            <View style={styles.textContainerStyle}>
                                <Text style={styles.textStyle}>{item.title}</Text>
                            </View>
                        </View>
                    </View>
                )
                }

            />

        </View>
    );
}
}

【讨论】:

  • 但是我在第一次获取数据时遇到了上述错误
  • 我第一次在渲染的控制台中得到“未定义”
  • componentDidMount 在第一次运行后调用,因此您需要检查数据长度。像 this.state.data.length > 0 ?然后渲染你的滑块:
  • 如果api中的数据发生变化,如何获取新数据?添加还是删除?
  • 有点小技巧,每当数据发生变化你需要删除旧数据,你需要发送一些推送通知类型的东西,收到更新推送通知后你需要删除数据,也就是存储。跨度>