我第一次使用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) is empty in the initDB() function)
,然后当我点击加载结果时,应用程序崩溃,因为this.realm
未定义。
我做错了什么?
答案 0 :(得分:2)
要访问域,您需要致电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'},
},
};