React Native 0.55.4渲染Firebase数据报错:Objects are not valid as a React child
解决React Native + Firebase读取数据时的"Objects are not valid as a React child"错误
我来帮你搞定这个问题!先看你遇到的错误提示,核心问题是你尝试把一个不符合要求的类型(这里是错误返回的字符串)当作React子元素渲染了,具体的问题出在代码的最后一行。
错误根源
你代码的最后一行是:
AppRegistry.registerComponent('itemlister', () => 'itemlister');
这里你返回的是一个字符串'itemlister',但AppRegistry.registerComponent的第二个参数需要返回你的React组件(也就是定义好的App类)。当React尝试渲染这个字符串对应的"组件"时,就会触发这个报错。
修复步骤
把最后一行改成:
AppRegistry.registerComponent('itemlister', () => App);
额外验证建议(确保数据渲染正常)
虽然你的getItems方法逻辑看起来没问题,但可以加个小验证确保数据结构正确:
- 在
getItems方法里添加console.log(items),确认生成的数组每个元素都是包含title和_key的简单对象,没有嵌套的复杂对象 - 检查Firebase Realtime Database里的
items节点,确保每个子项都存在title字段
修正后的完整代码
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) { 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', () => App);
这样修改后,应该就能正常渲染你的杂货清单了。另外提一句,React Native 0.55.4是比较旧的版本了,如果后续有机会可以考虑升级到较新的稳定版本,能获得更多特性和bug修复哦。
内容的提问来源于stack exchange,提问作者Kalyani Pullela
相关产品推荐
相关产品推荐

