【问题标题】:How does the list property of realm work?领域的列表属性如何工作?
【发布时间】:2017-09-29 21:48:36
【问题描述】:

我无法使用领域创建列表以便将其与领域 ListView 一起使用。

我需要制作2或3个ListView,你可以看下面的代码:

realm.js:

const Realm = require ('realm');

class UserEntrySchema extends Realm.Object {}
UserEntrySchema.schema = {
   name:'User',
   primaryKey:'id',
   properties:{
     id:'int',
     name:'string',
     username: 'string',
     email: 'string',
   }
};

class UserListSchema extends Realm.Object {}
UserListSchema.schema = {
  name:'UserList',
  properties: {
    users :{type:'list', objectType:'User'}
  }
};

class HistorySchema extends Realm.Object {}
HistorySchema.schema = {
  name : 'History',
  properties :{
    items : {type:'list',objectType:'User'}
  }
};

export default new Realm({
  schema:[UserEntrySchema,UserListSchema,HistorySchema], schemaVersion:0});

我用以下代码创建了第一个 ListView:

export default class SearchTabScreen1 extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchText:'',
      data:[]
    };
}

  componentDidMount(){
    this.fetchUsers();
  }

  fetchUsers(){
    console.log("FEEEEEETCH");
    fetch('http://jsonplaceholder.typicode.com/users')
        .then((response) => response.json())
        .then((responseJson) =>  {
          this.setState({
            data : responseJson
          });
          var data = this.state.data;
          realm.write(() => {
            for (var i = 0; i < data.length; i++){
              let myUser = realm.create('User',data[i],true);
         }
         console.log("ALLUSER", realm.objects('User'));
       });
      })
        .catch(function(e) {    // Failure callback registartion
              alert('Failure fetching data');
              console.log(e)
    });
  }

我尝试使用

创建一个列表属性

用户列表架构

没有成功。

现在这个 ListView 工作正常,即使我正在使用

realm.objects('用户')

作为数据源。

我不知道这样做好不好。

第二个 ListView 是“搜索历史”,当单击第一个 ListView 的一行时,它会调用以下方法来推送另一个屏幕(我使用的是 react-native-navigation 包)并填充领域列表。我想将此列表用作“历史列表视图”的数据源。

onPushPress(rowData) {
    this.props.navigator.showModal({
      title: "Random Title",
      screen: "Project.WordDefinition",
      passProps: {
        definition: rowData.name
      }
    });
      realm.write(() => {
      let historyList = realm.create('History',{},true);
      historyList.items.push({rowData});
    });
  }
}

我收到了这个错误:

“属性”必须是数字类型

我也试过了:

onPushPress(rowData) {
    console.log("ROWDATA", rowData);
    this.props.navigator.showModal({
      title: "Titre",
      screen: "AccessiDico.WordDefinition",
      passProps: {
        definition: rowData.name
      }
    });
      realm.write(() => {
      let historyList = realm.create('History',{},true);
      historyList.items.push({
        id:rowData.id,
        name:rowData.name,
        username: rowData.username,
        email: rowData.email,
      });

      console.log("ROWDATA",rowData);
      console.log("ITEMS",realm.objects('History'));
      console.log("List",historyList.items);
    });
  }
}

我得到了这个错误:

尝试使用现有的主对象创建“用户”类型的对象 关键价值

这是否意味着我不能使用“UserEntrySchema”中的“我的用户”将他们推送到领域列表中?

我真的很感激一些帮助,我已经有一个星期很难坚持这个了:+1:

谢谢!

PS:这里的历史ListView是如何编码的:

export default class HistoryTabScreen2 extends Component {
  constructor(props) {
    super(props);
    // if you want to listen on navigator events, set this up
    //this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this));
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
        postDataSource: ds.cloneWithRows(realm.objects('History')),
    };
  }

  renderRow(rowData, sectionId, rowId, highlightRow){
    return(
    <TouchableHighlight onPress={this.onPushPress.bind(this)}>
      <View style={styles.row}>
        <Text style={styles.rowText}>{rowData.name}</Text>
      </View>
    </TouchableHighlight>
    )
  }


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

当我单击 ListView 的一行时,我的 rowData 的日志:

'ROWDATA', { id: 5,

   name: 'Chelsey Dietrich',

   username: 'Kamren',

   email: 'Lucio_Hettinger@annie.ca',

   address: 

    { street: 'Skiles Walks',

      suite: 'Suite 351',

      city: 'Roscoeview',

      zipcode: '33263',

      geo: { lat: '-31.8129', lng: '62.5342' } },

   phone: '(254)954-1289',

   website: 'demarco.info',

   company: 

    { name: 'Keebler LLC',

      catchPhrase: 'User-centric fault-tolerant solution',

      bs: 'revolutionize end-to-end systems' } }

【问题讨论】:

标签: android list listview react-native realm


【解决方案1】:

我刚刚回答了一个关于列表对象的问题。 看看这个链接,如果需要,请进一步澄清。在帖子的最后,我提供了一个从领域列表对象创建/修改/附加/删除对象的工作示例。 How can I properly copy objects from one Realm object to another object

创建列表非常简单,这是最简单的情况:

class Letters: Object {
    var letterList = List<Letter>()
}

所以要创建一个列表,您需要知道您将使用的 Object 子类。 (上例中的字母)。

要添加到列表中,请创建一个对象(项目 - 下面),然后附加到列表中:

firstList.letterList.append(item)

【讨论】:

  • 嗨,你的回答。只要我可以在没有它的 ListViews 中显示数据库内容,我就选择不使用列表属性。我只是用realm.objects('dbName') 设置我的ListView 的数据源并用cloneWithRows(realm.objects('dbName') 更新它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
相关资源
最近更新 更多