React Native 使用Realm數據庫組件

本文原創首發於公衆號:ReactNative開發圈javascript

Realm是一款專爲移動​端開發的高性能數據庫。支持React-Naitve,支持 iOS 和 Android。官網文檔地址:https://realm.io/docs/javascr...java

前提

  • 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。node

clipboard.png

問題

在第一次編譯時須要下載依賴,可是因爲我國網絡問題,下載速度很慢,因此就會編譯失敗,通常會報如下錯誤:react

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

解決方法

就是手動從上面的連接地址去下載realm-sync-cocoa-1.0.3.tar.xz或者從別人電腦上拷貝過來,放到對應的目錄下便可。如今問題的關鍵是找到對應的目錄。
先找到你項目目錄下的/node_modules/realm/scripts/download-core.sh,打開該文件,找到download_core方法,在mkdir -p "$TMP_DIR」代碼下面添加這三行代碼:數據庫

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

這三行代碼的目的就是打印出臨時目錄的路徑。添加完後保存文件,而後從新執行react-native run-ios,這時候終端上面就會打印出臨時目錄的路徑。直接將下載的壓縮文件複製到對應的目錄下便可。npm

clipboard.png

相關文章
相關標籤/搜索