境界React Native-实施自动更新的最佳实践? [英] Realm & React Native - Best practice to implement auto-updates?

查看:258
本文介绍了境界React Native-实施自动更新的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是使Realm在React Native应用程序中成为响应式数据源的最佳实践/模式?特别是对于呈现和容器组件模式?

What are the best practices/patterns make realm a reactive datasource in a react native app? Especially for presentational and container components pattern?

以下是我想做出反应的示例: React Native的领域

Here is an example which I'd like to make reactive: Realm with React Native

有关自动更新/更改事件的文档有点薄,并且官方示例(据我所知)未使用此功能.

The docs on auto-updates/change-events are a bit thin and the official example does not make use of this feature (to my knowledge).

推荐答案

您可以通过订阅事件并在收到更改事件时更新ui来使示例具有反应性.现在,仅在提交写事务时才发送事件,但将来会添加更细粒度的更改事件.现在,您可以添加以下构造函数以在更改时更新ui:

You can make your example reactive by subscribing to events and updating the ui when you receive a change event. Right now events are only sent when write transactions are committed, but finer grained change events will be added in the future. For now you could add the following constructor to update the ui on changes:

constructor(props) {
  super(props);
  this.realm = new Realm({schema:[dogSchema]})
  this.realm.addListener('change', () => {
    this.forceUpdate()
  });
}

您需要保留Realm实例以使通知保持活动状态,并且可以在其余组件中使用该Realm实例.

You need to hold onto a Realm instance to keep the notifications alive, and you can use this Realm instance throughout the rest of the component.

代替调用forceUpdate,您可以改为在事件侦听器中设置组件的状态或道具以触发刷新,如下所示:

Instead of calling forceUpdate, you could instead set the component's state or props within the event listener to trigger the refresh, like so:

constructor(props) {
  super(props);

  this.realm = new Realm({schema:[dogSchema]})

  this.state = {...}; // Initial state of component.

  this.realm.addListener('change', () => {
    this.setState({...}); // Update state instead of using this.forceUpdate()
  });
}

这篇关于境界React Native-实施自动更新的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆