簡體   English   中英

如何在FlatList中接收AsyncStorage項目?

[英]How to receive the AsyncStorage items in FlatList?

我要做的是在FlatList中顯示保存在AsyncStorage中的項目。

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) {
}
};

您可以使用state並在componentDidMount對其進行初始化:

state = {
  data: [],
}

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

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

另外,如果您使用Redux,則可以在任何地方調用AsyncStorage.getItem並調度一個操作來填充商店, FlatList組件可以連接到該商店並顯示數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM