我有一个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