如何接收 FlatList 中的 AsyncStorage 项目? [英] How to receive the AsyncStorage items in FlatList?

查看:54
本文介绍了如何接收 FlatList 中的 AsyncStorage 项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是在 FlatList 中显示保存在 AsyncStorage 中的项目.

What I want to do is show the items saved in AsyncStorage in a FlatList.

savePosts = async () => {
try {
    let post = {
        postId: '1',
        postTitle: 'This is an example',
    }
    const posts = await AsyncStorage.getItem('posts') || '[]';
    posts = JSON.parse(posts);
    posts.push(post);
    AsyncStorage.setItem('posts', JSON.stringify(posts)).then(() => {
    });
} catch(error) {
}
};

推荐答案

可以在componentDidMount中使用state并初始化:

You can use state and initialise it in componentDidMount:

state = {
  data: [],
}

componentDidMount() {
  AsyncStorage.getItem('posts').then(data => this.setState({ data }));
}

<FlatList data={this.state.data} ...otherProps />

或者,如果您使用 Redux,您可以在任何地方调用 AsyncStorage.getItem 并分派一个操作来填充存储,FlatList 组件可以连接到该存储并显示数据.

Alternatively, if you use Redux, you can call AsyncStorage.getItem anywhere and dispatch an action to populate the store, which the FlatList component can connect to and display the data.

这篇关于如何接收 FlatList 中的 AsyncStorage 项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆