как сделать коллекцию детей с помощью массива - PullRequest
0 голосов
/ 31 мая 2018

Я создаю приложение со списком продуктов, в котором внешний интерфейс является реагирующим, а внутренний - firebase. В списке продуктов должны быть добавлены элементы.Я сохранил некоторые элементы в базе данных Firebase и извлекаю их из магазина, но появляется ошибка:

Ошибка

Объекты недопустимы какРеагировать на дочерний объект (найдено: объект с ключами ($$ typof, key, ref, props, _owner, _store). Если вы хотите отобразить коллекцию дочерних элементов, используйте вместо этого массив.

I 'm, использующая версиюact-native 0.55.4., пожалуйста, помогите мне.

это файл index.js

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  ListView,TouchableHighlight,AppRegistry
} from 'react-native';
import * as firebase from 'firebase';
import ToolBar from './app/components/ToolBar/ToolBar';
const styles = require('./app/style');

const firebaseConfig = {
  apiKey: 'AIzaSyClhqB9TEEffc4szIHUEVt0OqXvKQOEwxQ',
    authDomain: 'grocerryapp-fbe06.firebaseapp.com',
    databaseURL: 'https://grocerryapp-fbe06.firebaseio.com',
    projectId: 'grocerryapp-fbe06',
    storageBucket: 'grocerryapp-fbe06.appspot.com',
    messagingSenderId: '903884995524'
}
const firebaseApp = firebase.initializeApp(firebaseConfig);


export default class App extends Component {
  constructor(){
    super();
    let ds= new ListView.DataSource({rowHasChanged:(r1,r2) => r1 !== r2});
    this.state={
      itemDataSource:ds
    }

    this.itemsRef = this.getRef().child('items');
    this.renderRow = this.renderRow.bind(this);
    this.pressRow = this.pressRow.bind(this);
  }
  getRef(){
    return firebaseApp.database().ref();
  }
  componentWillMount() {
    this.getItems(this.itemsRef);
  }
  componentDidMount() {
    this.getItems(this.itemsRef);
  }
  getItems(itemsRef) {
    //let items = [{title: 'Item One'},{title: 'Item Two'}];
    itemsRef.on('value',(snap) => {
      let items = [];
      snap.forEach((child) => {
        items.push({

          title: child.val().title,
          _key: child.key

        });
      });
      this.setState({
        itemDataSource: this.state.itemDataSource.cloneWithRows(items)
      });
    });
  }
  pressRow(item){
    console.log(item);
  }
renderRow(item){
  return(
    <TouchableHighlight onPress={() => {
      this.pressRow(item);
    }}>
<View style={styles.li}>
<Text style={styles.liText}>{item.title}</Text>
</View>
    </TouchableHighlight>
  );
}


  render() {
    return (
      <View style={styles.container}>
      <ToolBar title="Item Lister" />
      <ListView
        dataSource={this.state.itemDataSource}
        renderRow={this.renderRow}

      />
            </View>
    );
  }
}


AppRegistry.registerComponent('itemlister', () => 'itemlister');

Ответы [ 3 ]

0 голосов
/ 31 мая 2018

Я думаю, что это асинхронная проблема.Ваш setState запускается до того, как ваш forEach завершил работу, и поэтому ваши this.state.itemDataSource.cloneWithRows (items), items неполные.

getItems(itemsRef) {
//let items = [{title: 'Item One'},{title: 'Item Two'}];
itemsRef.on('value',(snap) => {
  let items = [];
  snap.forEach((child) => {
    items.push({

      title: child.val().title,
      _key: child.key

    });
  });
  this.setState({
    itemDataSource: this.state.itemDataSource.cloneWithRows(items)
  });
});

}

Вы могли бы ...

getItems(itemsRef) {
//let items = [{title: 'Item One'},{title: 'Item Two'}];
itemsRef.on('value',(snap) => {
let items = [];
snap.forEach((child) => {
  items.push({

    title: child.val().title,
    _key: child.key

  });
});
}.then(() => {
  this.setState({
    itemDataSource: this.state.itemDataSource.cloneWithRows(items)
  })
})

});
}
0 голосов
/ 17 июня 2018

Я видел эту ошибку, и я думаю, она связана с библиотекой firebase!Текущая версия содержит ошибки, поэтому используйте версию 5.0.2!

npm install --save firebase@5.0.2
0 голосов
/ 31 мая 2018

return () поможет вам

 render() {
  return (
    <View style={styles.container}>
    <ToolBar title="Item Lister" />
    <ListView
      dataSource={this.state.itemDataSource}
      renderRow={(rowData) => {
       return(
        <View>
          <TouchableHighlight 
          onPress={() => this.pressRow(rowData)}
          >
           <View style={styles.li}>
             <Text style={styles.liText}>{item.title}</Text>
           </View>
          </TouchableHighlight>
       </VIew>
       )
      }}
    />
    </View>
 );
 }
...