【问题标题】:React Native ListView with Realm ResultsReact Native ListView 与领域结果
【发布时间】:2016-11-28 02:20:56
【问题描述】:

我正在尝试创建一个 react-native ListView 来呈现 Realm 返回的结果。我一直按照我找到的有关 react-native 的 ListView 以及如何使用 Realm 的说明进行操作。

但是我总是遇到同样的错误:Objects are not valid as a React child (found: [object Results]). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of 'Text'.

根据我从 Realm 文档和其他文章中了解到的结果,Results 对象应该表现得像一个 javascript 列表,因此应该被 cloneWithRows 方法所接受。

如果有人能告诉我我做错了什么或如何解决这个问题,我们将不胜感激。

附:我已经尝试过 react-native 的 ListView 和 Realm 的 ListView 并且两者的行为方式相同。

import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    Text,
    Navigator,
    TouchableHighlight,
    TouchableOpacity,
    //ListView,
} from 'react-native';
import { ListView } from 'realm/react-native';

import realm from './myrealm'

class contextview extends Component {
    getState() {
        console.log("getInitialState");
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        let pictures = [ realm.objects('picture').filtered('new == true') ];
        console.log("pictures: " + pictures);
        return {
            //dataSource: ds.cloneWithRows(['row 1', 'row 2', 'row 3']),
            dataSource: ds.cloneWithRows(pictures)
        };
    }

    constructor(props)
    {
        super(props);
        this.state = this.getState();
        this.bindMethods();
    }

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

【问题讨论】:

    标签: javascript react-native realm react-native-listview


    【解决方案1】:

    您在调用cloneWithRows 时是否收到此错误?如果是这样,您可能需要在使用Realm.ListView 时在Realm.Results 对象的快照上调用cloneWithRows。这是在领域示例here 中完成的。所以也许尝试使用Realm.ListView 并将您的代码更改为:

    let pictures = [ realm.objects('picture').filtered('new == true').snapshot() ];
    

    【讨论】:

    • 感谢您的建议。我试过了,它并没有改变任何东西,最终导致我找到了错误的原因。
    【解决方案2】:

    我在我的渲染方法中找到了原因,

    代替:

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

    我应该做的:

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

    由于rowData 是一个对象,ReactNative 无法在 Text 元素中呈现它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      相关资源
      最近更新 更多