React Native 使用Realm数据库组件

时间:2022-06-05
本文章向大家介绍React Native 使用Realm数据库组件,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Realm是一款专为移动端开发的高性能数据库。支持React-Naitve,支持 iOS 和 Android。官网文档地址:https://realm.io/docs/javascript/latest/。

前提

  • React Native的版本要大于等于0.31.0

安装

npm install --save realm
react-native link realm

示例代码

const Realm = require('realm');

class <project-name> extends Component {
  constructor(props) {
    super(props);
    this.state = { realm: null };
  }

  componentWillMount() {
    Realm.open({
      schema: [{name: 'Dog', properties: {name: 'string'}}]
    }).then(realm => {
      realm.write(() => {
        realm.create('Dog', {name: 'Rex'});
      });
      this.setState({ realm });
    });
  }

  render() {
    const info = this.state.realm
      ? 'Number of dogs in this Realm: ' + this.state.realm.objects('Dog').length
      : 'Loading...';

    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          {info}
        </Text>
      </View>
    );
  }
}

调试

使用Realm Studio来调试查看编辑数据库里的数据,支持Mac、Windows、Linux。

问题

在第一次编译时需要下载依赖,但是由于我国网络问题,下载速度很慢,所以就会编译失败,一般会报以下错误:

Downloading dependency: sync 1.0.3 https://static.realm.io/downloads/sync/realm-sync-cocoa-1.0.3.tar.xz Downloading sync failed. Please try again once you have an Internet connection. Command /bin/sh failed with exit code 1

解决方法

就是手动从上面的链接地址去下载realm-sync-cocoa-1.0.3.tar.xz或者从别人电脑上拷贝过来,放到对应的目录下即可。现在问题的关键是找到对应的目录。 先找到你项目目录下的/nodemodules/realm/scripts/download-core.sh,打开该文件,找到downloadcore方法,在mkdir -p "$TMP_DIR”代码下面添加这三行代码:

echo "$TMP_DIR"
    echo "$TMP_TAR"
    echo "$TAR"

这三行代码的目的就是打印出临时目录的路径。添加完后保存文件,然后重新执行react-native run-ios,这时候终端上面就会打印出临时目录的路径。直接将下载的压缩文件复制到对应的目录下即可。