我在React Native中遵循了领域db教程,并且成功从DB创建,插入和删除数据,但是从数据库读取时遇到问题。
我总是会得到相同的结果,但无法解决且没有用。
我检查了很多代码,但我找不到我的错误。
这是我的代码:
database.js
import Realm from 'realm';
export const HEART_QUEUE_SCHEMA = 'HeartQueue';
export const HeartQueueSchema = {
name : HEART_QUEUE_SCHEMA,
primaryKey : 'id',
properties: {
id : 'int', // primary key
requestTime : {type : 'string', indexed: true}
}
};
const databaseOptions = {
path: 'mizWord.realm',
schema : [HeartQueueSchema],
schemaVersion : 0,
}
export const insertToHeartQueue = (item) => new Promise((resolve, reject) => {
Realm.open(databaseOptions).then(realm => {
realm.write(()=>{
realm.create(HEART_QUEUE_SCHEMA, item);
resolve(item);
})
}).catch((error) => reject(error));
});
export const updateHeartQueue = (item) => new Promise((resolve, reject) => {
Realm.open(databaseOptions).then(realm => {
realm.write(()=>{
let updatingRow = realm.objectForPrimaryKey(HEART_QUEUE_SCHEMA, item.id);
updatingRow.requestTime = 'hello world';
resolve();
})
}).catch((error) => reject(error));
});
export const deleteHeartQueue = (itemID) => new Promise((resolve, reject) => {
Realm.open(databaseOptions).then(realm => {
realm.write(()=>{
let updatingRow = realm.objectForPrimaryKey(HEART_QUEUE_SCHEMA, itemID);
realm.delete(updatingRow);
resolve();
})
}).catch((error) => reject(error));
});
export const deleteAllHeartQueue = () => new Promise((resolve, reject) => {
Realm.open(databaseOptions).then(realm => {
realm.write(()=>{
let updatingRows = realm.objects(HEART_QUEUE_SCHEMA);
realm.delete(updatingRows);
resolve();
})
}).catch((error) => reject(error));
});
export const getAllHeartQueue = () => new Promise((resolve, reject) => {
Realm.open(databaseOptions).then(realm => {
let allHeartsList = realm.objects(HEART_QUEUE_SCHEMA);
resolve(allHeartsList);
}).catch((error) => reject(error));
});
export default new Realm(databaseOptions)
这是我的app.js文件
import realm from './databases';
import {insertToHeartQueue, deleteHeartQueue, deleteAllHeartQueue, getAllHeartQueue} from './databases'
export default class App extends Component {
constructor(){
super();
this.state = {
data : "test",
time : 0,
testDB : '',
xxxz : []
}
}
_readDB = () => {
getAllHeartQueue().then((allHeartsList)=>{
console.log('data',allHeartsList);
this.setState({
xxxz : allHeartsList
})
}).catch((err)=>{
alert(err)
});
}
render() {
console.log('state', this.state.xxxz)
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.welcome}>{this.state.time}</Text>
<View>
<Button
onPress={()=> this._readDB()}
title="Ask for Data"
color="#cc77v"
accessibilityLabel="Learn more about this purple button"
/>
<View>
</View>
</View>
</View>
);
}
}
bu我总是这样: 代理服务器{类型:“对象”,可选:false,符号(境界):140510983537104,符号(id):175,…}
答案 0 :(得分:1)
尝试在写交易之外爱resolve()
。