Realm js运行异步查询

3
我正在使用 React-NativeRealm Database。我尝试使用 async/await 模式运行读取查询,但似乎它总是同步执行,导致UI冻结,因为查询至少需要几秒钟才能呈现(由于可能存储了大量数据)。
这是我正在使用的代码(这只是复制和粘贴,但可以给你一个想法),我是否遗漏了什么?
export default class CustomComponent extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     value:0
   };
   this.realm = this.buildRealm();
 }

  buildRealm() {
        return new Realm({ schema: [EventSchema] });
 }

  componentWillMount() {
    this.fetchData().then(result => { this.setState(value:result);});
  }

  async fetchData() {    
    var appState = await someMethod()
    return appState;
  }

  someMethod() {
   return new Promise(resolve => {
         resolve(queryFromDB())
        });
  }

  queryFromDB() {
     // Returns a value fetched from Realm
     let events = this.realm.objects("Event");
     return events.length;
   }

  render() {
   return (
     <Text> {this.state.value} </Text> 
   );
  }
}
2个回答

1

Realm查询是同步的,无法使其异步化。 看起来你正在使用React Native与Realm,如果是这种情况,最好的解决方案是使用交互管理器延迟您的Realm查询。

async componentDidMount() {
  // loading objects from realm is a synchronous task that block the main
  // process, in order not to freeze the ui, we trigger the load after
  // the interactions and screen loading is done
  this.getRealmDataHandle = InteractionManager.runAfterInteractions(() => this.getRealmData())
}

componentWillUnmount() {
  if (this.getRealmDataHandle !== undefined) {
    this.getRealmDataHandle.cancel()
  }
}

首先,您的组件将挂载并呈现加载屏幕,然后当UI渲染线程完成其工作时,交互管理器将触发realm查询。这样,用户就不会经历太多UI冻结。
我希望有一天realmJS团队能提供一个异步版本,但我怀疑这很快就会发生。

0

你试过在 componentDidMount 而不是 willMount 上获取数据吗?

willMount 要求你的函数在挂载开始之前完成。

然后你可以添加一个加载中的 UI 状态(旋转图标、示例文本等)。

然后也许将你的 state.value 设置为默认值,当查询完成时再更新它。


实际上不会,但我会试试看。 - r4id4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接