领域数据更改时如何更新React Native ListView [英] How to update React Native ListView when Realm data changes

查看:109
本文介绍了领域数据更改时如何更新React Native ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储在Realm DB中的活动"对象的列表,这些对象显示在ListView上. 最初加载数据并将其显示在屏幕上没有问题.但是,当数据更新时(在另一个屏幕中,我们称其为详细编辑屏幕"),并且用户返回到列表屏幕时,列表不会更新.

I have a list of 'Activity' objects stored in a Realm DB which are showing on a ListView. There is no problem initially loading the data and showing it on the screen. However, when the data update (in another screen, lets call it 'detail edit screen') and the user returns to the list screen, the list isn't updated.

我试图在render方法中设置setState,但是返回一个空白屏幕.

I tried to setState inside the render method, but that returns a blank screen.

    var activities = realm.objects('Activity').sorted('date');
    let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); 
    ...
    module.exports = React.createClass({
      getInitialState: function(){
        return { 
          dataSource: ds.cloneWithRows(activities),
        };
      },
    ...
    render: function(){
       //update the list of activities
        activities = realm.objects('Activity').sorted('date'); 
        this.setState({dataSource: ds.cloneWithRows(activities)});
         return ( 
          <View>
              {(!activities || activities.length<1) && noActivitiesMessage}
                  <ListView style={styles.listStyle} dataSource={this.state.dataSource} 
            renderRow={this._renderRow} />
    </View>

)
...
}

推荐答案

我遇到了与您相同的问题.我的问题是使用Realm ListView解决的.我这样使用

I had the same problem like you. My problem was solve by using the Realm ListView. I use it like this

import { ListView } from 'realm/react-native';

class List extends Component {

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    src = realm.objects('MyObject');
    this.setState({
      dataSource:this.state.dataSource.cloneWithRows(src),
      data:src
    });
  } 

  updateData(){
   // update or add object in Realm
   this.setState({
     dataSource:this.state.dataSource.cloneWithRows(this.state.data)
   });
  } 

  render(){
    return( 
        <ListView
          dataSource={this.state.dataSource}
          renderRow=... />
  }
}

这篇关于领域数据更改时如何更新React Native ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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