react-native - 为什么 realm 对象在 react-native 中未定义

标签 react-native realm

我是第一次使用 Realm,我只是想初始化一个数据库并向其中写入一条记录。这是我的代码。

import React, { Component } from 'react';
import {StackNavigator} from 'react-navigation';
import Realm from 'realm';


import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Linking
} from 'react-native';

class Home extends Component {
  static navigationOptions = {
    title: 'Login',
    headerStyle: {
        backgroundColor:'#000000'
    },
    headerTitleStyle: {
        color:'#fff'
    }
  };
  initDB()
  {
    const realm = new Realm({schema: [CompatibilityProduct]});
    this.realm = realm;
    console.log(realm);
  };
  loadResults()
  {
    const realm = this.realm;
    console.log(realm);
        // Write
    realm.write(() => {
        realm.create('CompatibilityProduct', {
            compatibilityId: 18,
            productId: 17,
        });
    });


  };
    constructor(props)
    {
        super(props);
    }
  render() {
    const {navigate} = this.props.navigation;
    return (
      <View>
        <Text onPress={this.initDB}>
             Init DB
        </Text>
        <Text onPress={this.loadResults}>
             Load Results
        </Text>
      </View>
    );
  }
}

const myscreens = StackNavigator({
  Home: {screen: Home}
});

class CompatibilityProduct {}
CompatibilityProduct.schema = {
    name: 'CompatibilityProduct',
    properties: {
        compatibilityId: {type: 'int'},
        productId: {type: 'int'},
    },
};


export default myscreens;

我在我的 AVD 中启动应用程序,我点击 Init DB (console.log(realm) 在 initDB() 函数中为空),然后当我点击 Load Results 时,应用程序崩溃,因为 this.realm 未定义。

我做错了什么?

最佳答案

要访问 Realm ,您需要调用 Realm.Open().then() ... 把你的代码改成这样

 class Home extends React.Component {
  constructor(props) {
   super(props);
   this.state = { realm: null }; // initial the state with null
  }
  initDB()
  {
   Realm.open({ // open connection
     schema: [CompatibilityProduct]
   }).then(realm => { // here is realm
    console.log('realm1', realm);
    this.setState({ realm });  // set it to state
   });
  };
 loadResults()
  {
const {realm } = this.state; // access it from state
console.log('realm2', realm);
    // Write
realm.write(() => { // write to it
    realm.create('CompatibilityProduct', {
        compatibilityId: 18,
        productId: 17,
    });
  });
  this.setState({ realm }); // set it to state to see updates
};

render() {
// read data from it
const info = this.state.realm ? 'Number of CompatibilityProduct in this Realm: ' + this.state.realm.objects('CompatibilityProduct').length : 'Loading...';

return (
  <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
    <Text onPress={this.initDB.bind(this)}> // bind to access this
         Init DB
    </Text>
     <Text onPress={this.loadResults.bind(this)}> // bind to access this
         Load Results {info}
      </Text>
    </View>
  );
 }
}


const CompatibilityProduct = { // schema is object not class
   name: 'CompatibilityProduct',
    properties: {
    compatibilityId: {type: 'int'},
    productId: {type: 'int'},
  },
 };

关于react-native - 为什么 realm 对象在 react-native 中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46372463/

相关文章:

javascript - 使用 async/await 获取 firebase.auth().currentUser

ios - 使用 cocoapods 时 Realm.io 构建错误 `use_frameworks!`

ios - 在 Realm 中存储来自 API 的数据

c# - Realm :自增主键

javascript - 在 UIManager 中找不到 "RNCSafeAreaView"

ios - React-native@0.26.3 需要 react@15.0.2 的对等点,但没有安装

react-native - 使用 android-studio 安装时,在模拟器上运行的 React Native Android 应用程序不会连接到 Metro bundler

react-native - 重新加载热键cmd + r不起作用

ios - 从不同的线程/ session 更新 Swift 中的 Realm 对象

android - 使用Kotlin Coroutines和Realm执行数据库写入会导致UI卡住