[英]How to save an array of Items in AsyncStorage React Native?
我要制作的是书签列表,但我不知道如何在AsyncStorage中保存一系列项目,我的技能是做出反应的基础。
当我按下“保存到书签”按钮时,我只需要用于保存帖子(帖子图像,标题和ID)的功能。
export default class PostDetails extends Component {
constructor(props) {
super(props);
const {params} = props.navigation.state;
this.state = {
item: params.item
};
}
render() {
const {item} = this.state;
return (
<Image source={{uri: item.post_image}}/>
<Text> {item.post_id} </Text>
<Text> {item.post_title} </Text>
<Button>
<Text> Save to Bookmark </Text>
</Button>
);
}
}
我认为您想使用JSON.stringify(arrayToSave)
; 请参阅JSON.stringify()
的文档 。 它将数组转换为JSON字符串,该字符串可以保存到AsyncStorage
,然后在以后的阶段进行检索。
const saveBookmarks = async (bookmarksArray) => {
try {
const bookmarksString = JSON.stringify(bookmarksArray);
await AsyncStorage.setItem('@MyStore:bookmarks',bookmarksString);
} catch (error) {
// Error saving data
}
};
<Button onClick={() => saveBookmarks(yourArray)} />
要检索它,可以使用const theSavedArray = JSON.parse(stringFromAsyncStorage)
; JSON.parse()
的文档
try {
const bookmarksString = await AsyncStorage.getItem('@MyStore:bookmarks');
if (bookmarksString !== null){
// We have data!!
const bookmarksArray = JSON.parse(bookmarksString);
}
} catch (error) {
// Error retrieving data
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.