我正在从firebase中获取数据,并尝试以表格格式显示所有数据。
我发现ReactTable是一种将所有检索到的数据打印到列和行中的好方法,所以我选择了这种方法以表的形式打印数据。但它无法打印列和行中的数据,而是显示以下错误:
错误:元素类型无效,应为字符串(用于内置组件(或类/函数(用于复合元素(
如果代码错误,请更正并尝试解决我的问题,因为我尝试了这么长时间的代码,仍然无法解决错误。
import React, { Component } from 'react';
import { StyleSheet, View, Text } from 'react-native';
import ReactTable from 'react-table';
import firebase from 'firebase';
const firebaseConfig = {
apiKey: "XXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXX",
projectId: "XXXXX",
storageBucket: "XXXXX",
messagingSenderId: "XXXXX",
appId: "XXXX",
measurementId: "XXXX"
};
firebase.initializeApp(firebaseConfig);
export default class Form1 extends Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
componentDidMount() {
firebase.database().ref('users').on('value',snapshot => {
const data = [];
snapshot.forEach((childSnapShot) => {
const locker = {
email: child.val().email,
password: child.val().password,
// price: child.val().price,
};
data.push(locker);
});
this.setState(prevState => {
return { data: [...prevState.data, ...data] };
});
console.log(this.state.data)
});
}
render() {
const columns = [
{
Header: "email",
accessor: "email"
},
{
Header: "password",
accessor: "password"
}
];
return (
<div>
<ReactTable data={this.state.data} columns={columns} />
</div>
);
}
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#f1f8ff' },
text: { margin: 6 }
});
我在您的代码中发现了一些小错误并进行了更正。我认为您应该首先遵循Firebase和React文档,因为这些错误是非常基本的。如果这个答案对你有帮助,请告诉我。
import React, { Component } from 'react';
import { StyleSheet, View, Text } from 'react-native';
import ReactTable from 'react-table';
import firebase from 'firebase';
const firebaseConfig = {
apiKey: "XXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXX",
projectId: "XXXXX",
storageBucket: "XXXXX",
messagingSenderId: "XXXXX",
appId: "XXXX",
measurementId: "XXXX"
};
firebase.initializeApp(firebaseConfig);
export default class Form1 extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
columns: [
{
Header: "email",
accessor: "email"
},
{
Header: "password",
accessor: "password"
}
]
}
}
componentDidMount() {
const data = [];
var query = firebase.database().ref("users");
query.once("value").then((snapshot) => {
snapshot.forEach((childSnapshot, index) => {
let singleObj = {
email: childSnapshot.val().email,
password: childSnapshot.val().password,
}
data.push(singleObj);
if (index === snapshot.length - 1) {
this.setState({ data: data });
}
});
});
}
render() {
return (
<View>
{this.state.data.length > 0 && <ReactTable data={this.state.data} columns={this.state.columns} />}
</View>
);
}
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#f1f8ff' },
text: { margin: 6 }
});