【发布时间】:2018-06-16 00:54:10
【问题描述】:
我目前在使用 Firebase 和使用状态时遇到了一些问题。是的,我想指出我是 React 新手。基本上我想要实现的是显示所有发送给我的inquiries,它们存储在firebase中。
为了实现这一点,我做了以下工作:
constructor(props) {
super();
this.fetchMessage = this.fetchMessage.bind(this);
this.state = {
messages: []
};
}
fetchMessage = () => {
const database = firebase.database();
const inquiries = [];
database.ref('inquiries').on('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
inquiries.push({
id: childSnapshot.key,
fullName: childSnapshot.val().fullName,
email: childSnapshot.val().email,
message: childSnapshot.val().message,
subject: childSnapshot.val().subject,
dateSent: childSnapshot.val().dateSent
});
});
console.log(inquiries);
this.setState(() => {
return {
messages: inquiries
}
});
});
}
我要做的是将所有inquiries 存储在状态中,以便我可以运行for-loop 并在我的网站上显示所有内容。我该怎么做呢?
我的第一个想法是,如前所述:将每个对象存储在状态中,然后像 this.state.messages[0]、this.state.messages[1] 一样访问每个查询(以获取完整数组),然后通过执行 this.state.messages[0].fullName 显示每个值例如。
我怎样才能做到这一点?我目前的错误是:
[Error] Invariant Violation: Objects are not valid as a React child (found: object with keys {id, fullName, email, message, subject, dateSent}). If you meant to render a collection of children, use an array instead.
in h1 (created by AdminPanel)
in div (created by AdminPanel)
in AdminPanel (created by Route)
in Route
in Switch
in div
in Router (created by BrowserRouter)
in BrowserRouter
(anonymous function) (bundle.js:1530)
【问题讨论】:
-
你试过'this.setState({messages:inquiries});'代替?
-
@Dream_Cap 还是一样的问题..奇怪..
-
您能否添加呈现消息列表的代码。根据您的错误,我猜这就是它的位置
标签: arrays reactjs object state