WatermelonDB 詳細介紹
WatermelonDB,下一代 React 數據庫,可構建功能強大的 React 和 React Native 應用程序,可在保持快速的同時從數百個記錄擴展到數萬個記錄。
WatermelonDB 是一種在 React Native 和 React Web 應用中處理用戶數據的新方法。它針對在 React/React Native 中構建複雜應用進行優化,其首要目標是提高實際性能。簡單來說,就是保證的的應用必須快速啓動。
當你開始擴展到數千或數萬個數據庫記錄時,會發現對應用的啓動速度有很大影響,尤其是在速度較慢的 Android 設備上。WatermelonDB 通過惰性(lazy)來解決問題 —— 除非有要求,否則不加載。而且由於所有查詢都是直接以單獨的線程在穩定的 SQLite 數據庫上執行的,所以即使是在較慢的 Android 設備上,多數查詢也會在不到1毫秒的時間內解析,即使有 10,000 條記錄!
Usage
首先,定義模型
class Post extends Model {
@field('name') name
@field('body') body
@children('comments') comments
}
class Comment extends Model {
@field('body') body
@field('author') author
}
然後,將組件與數據連接:
const Comment = ({ comment }) => (
<View style={styles.commentBox}>
<Text>{comment.body} — by {comment.author}</Text>
</View>
)
// This is how you make your app reactive!
const enhance = withObservables(['comment'], ({ comment }) => ({
comment: comment.observe()
}))
const EnhancedComment = enhance(Comment)
即可進行渲染
const Post = ({ post, comments }) => (
<View>
<Text>{post.name}</Text>
<Text>Comments:</Text>
{comments.map(comment =>
<Comment key={comment.id} comment={comment} />
)}
</View>
)
const enhance = withObservables(['post'], ({ post }) => ({
post: post.observe(),
comments: post.comments.observe()
}))
本文來自雲棲社區合作伙伴“開源中國”
本文作者:局長