我有一個React項目設置爲從Firebase數據庫中獲取對象並將其呈現給我的頁面。但是我不知道如何正確渲染數據。在React中渲染JavaScript對象
的數據,我取這個樣子的:
{
"projects": {
"0": {
"title": "test",
"function": "test2"
},
"1": {
"title": "test3",
"function": "test4"
}
}
}
在Chrome陣營調試我看到這一點:
<div>
<Message key="0" data={function: "test2", title: "test", key: "0"}>...</Message>
<Message key="1" data={function: "test4", title: "test3", key: "1"}>...</Message>
</div>
但在元素瀏覽我只看到兩個空的div:
<div>
<div></div> == $0
<div></div>
</div>
目前我正在將<Message key={index} data={message} />
傳遞給包含的Message組件
編輯:因爲沒有消息丙更改這對{this.props.data}被傳遞給消息組件
重構的代碼:<div> key={index} data={message} </div>
然而返回錯誤
Objects are not valid as a React child (found: object with keys {function, title, key}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of ProjectList.
作爲項目項目有鍵我不相信CreateFragment是正確的解決方案。此外,Firebase支持通過陣列上的鍵傳遞對象,所以我給出的解決方案在這種情況下似乎不起作用。但是,我怎樣才能控制對象在頁面上的呈現方式?
我完全ProjectList組件看起來是這樣的:
import React from 'react';
import firebase from 'firebase';
import _ from 'lodash';
import Message from './Message'
class ProjectList extends React.Component {
constructor(props){
super(props);
this.state = {
messages: {}
};
this.firebaseRef = firebase.database().ref('projects');
this.firebaseRef.on("child_added", (msg)=> {
if(this.state.messages[msg.key]){
return;
}
let msgVal = msg.val();
msgVal.key = msg.key;
this.state.messages[msgVal.key] = msgVal;
this.setState({messages: this.state.messages});
});
}
render(){
var messageNodes = _.values(this.state.messages).map((message, index)=> {
return (
<Message key={index} data={message} />
);
});
return (
<div>
{messageNodes}
</div>
);
}
}
export default ProjectList;
謝謝!
編輯:將消息組件呈現更改爲{this.props.data}
,因爲消息組件不接收消息通道。
「消息」組件呈現什麼? – Blorgbeard
我所有的信息是:'constructor(道具){超級(道具); } render(){ return(
@dwigt'Message'沒有收到任何'message'道具。請將此片段添加到問題 – martriay