高性能React数据容器WatermelonDB

高性能React数据容器WatermelonDB_第1张图片
WatermelonDB

简介

WatermelonDB是React Native和React Web一种新的数据状态容器,虽然称作DB但意义和传统DB还是有些区别的,它的作用更像Redux,同Redux类似,WatermelonDB也是单一数据源原则,并且数据流单向的形式,UI会根据记录的变化而相应的改变。
WatermelonDB比Redux的优势在于,对于数据记录较大的React应用,能提供更好的性能表现。同时WatermelonDB也能比Redux更友好的管理数据流。

示例

首先,定义Models

class Post extends Model {
  @field('name') name
  @field('body') body
  @children('comments') comments
}

class Comment extends Model {
  @field('body') body
  @field('author') author
}

然后connect数据到components(和Redux connect比较像)

const Comment = ({ comment }) => (
  
    {comment.body} — by {comment.author}
  
)

// This is how you make your app reactive! ✨
const enhance = withObservables(['comment'], ({ comment }) => ({
  comment: comment.observe()
}))
const EnhancedComment = enhance(Comment)

render

const Post = ({ post, comments }) => (
  
    {post.name}
    Comments:
    {comments.map(comment =>
      
    )}
  
)

const enhance = withObservables(['post'], ({ post }) => ({
  post: post.observe(),
  comments: post.comments.observe()
}))

现在添加、更新、删除操作一条数据记录,绑定的component就会自动重新render了。
对于数据流大、应用复杂又比较追求性能的React应用,可以尝试一下WatermelonDB了。

安装文档:https://github.com/Nozbe/WatermelonDB/blob/master/docs/Installation.md

你可能感兴趣的:(高性能React数据容器WatermelonDB)