【问题标题】:Populate ReactNative ListView with Firebase data使用 Firebase 数据填充 ReactNative ListView
【发布时间】:2017-02-03 15:28:03
【问题描述】:

我已经为此苦苦挣扎了几天。我想用我的 Firebase 数据库中的数据填充 React Native 中的 ListView。我有这个设置:

const ListItem = require('./profileRow');

var database = firebase.database();
var userId, dataKey;



    class Selection extends Component {


      constructor(props) {
        super(props);

        userId = firebase.auth().currentUser.uid;

        this.dataRef = firebase.database().ref('/users/' + userId + '/profiles_info');

          this.state = {
            dataSource: new ListView.DataSource({
              rowHasChanged: (row1, row2) => row1 !== row2,
            })
          };

      }

      listenForProfiles(dataRef){
        dataRef.on('value', (snap) => {

          var profiles = [];
          snap.forEach((child) => {
            profiles.push({
              name: child.val().forename,
              _key: child.key
            });
          });
          alert(profiles);
          this.setState({
            dataSource: this.state.dataSource.cloneWithRows(profiles)
          });
        });
      }

      componentDidMount() {
        this.listenForProfiles(this.dataRef);
      }

      render() {


          return (
            <Image source={require('../assets/bg.png')} style={styles.container}>

            <View style={{flex: 1, flexDirection:'column'}}>
            <Text>
              Select a profile to view:
            </Text>

            </View>

            <View style={{flex: 1}}>

            <ListView dataSource={this.state.dataSource} renderRow={this._renderItem.bind(this)} enableEmptySections={true} style={styles.listview}> </ListView>

            </View>

            </Image>
          );

      }

      _renderItem(item) {
        return (
          <ListItem item={item}/>
        );
      }

    }

数据结构如下所示:

所以我在这里要做的是用每个“配置文件”目录(0、1、2)的“名字”字符串填充 ListView 的每一行。 但是在我的 alert() 上,我返回:[object Object],[object Object],[object Object] 这一定意味着它只是从“profiles_info”中获取目录作为对象,而不是从这些目录中获取每个“名字”字符串。

这是我卡住的地方,我希望有人能对此有所了解。我知道解决方案应该是什么,只是不知道如何在代码中应用它。

提前致谢!

【问题讨论】:

    标签: firebase react-native firebase-realtime-database


    【解决方案1】:

    您在此处将对象推送到您的配置文件数组中,因此您的警报显示对象是有道理的:

    profiles.push({
        name: child.val().forename,
        _key: child.key
    });
    

    如果您使用alert(JSON.stringify(profiles)); 而不是alert(profiles);,您应该会看到包含字段namekey 的对象数组。访问 profiles[0].name 将给出实际名称。

    附注,如果您使用console.log 而不是alert,您会得到一些更有意义的信息。

    【讨论】:

    • 谢谢杰夫,终于搞定了。
    【解决方案2】:

    尝试遵循教程。可能对你有帮助。

    react-native-firebase-tutorial-list

    【讨论】:

    • 谢谢,但我之前看过它,而且我基本上使用的方法与该教程演示的方法相同。我的问题更多是关于如何遍历正确的目录并将每个目录中的特定数据提取到我的 Listview 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    相关资源
    最近更新 更多