2016-08-24 46 views
2

我有一个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},因为消息组件不接收消息通道。

+0

“消息”组件呈现什么? – Blorgbeard

+0

我所有的信息是:'constructor(道具){超级(道具); } render(){ return(

{this.props.message}
) }' – dwigt

+0

@dwigt'Message'没有收到任何'message'道具。请将此片段添加到问题 – martriay

回答

3

Message渲染方法更改为:

render() { 
    return <div>{this.props.data}</div> 
} 
+0

谢谢,我相信这是解决方案的一部分。然而,我仍然收到错误'对象作为一个React孩子无效(找到:带有键{函数,标题,键}的对象)' – dwigt

+0

你能用代码更新问题吗?没有它,我无法帮助你 – martriay

0

你的名字data传递道具邮件组件与使用this.props.message这是错误的渲染它。

使用this.props.data

export default class Message extends React.Component { 

constructor(props){ 
    super(props); 
} 
render(){ 
    return ( 
     <div> {this.props.data} </div> 
    ) 
} 

} 
0

关于错误`对象作为React子项(找到:有键{function,title,key}的对象)是无效的。我把我的道具从一个物体改成了一个数组。最后,我将消息组件更改为this.props.data,因为其他海报都没有注意到消息通道没有通过。

阵列的解决办法:

class ProjectList extends React.Component { 
    constructor(props){ 
    super(props); 
    this.state = { 
     messages: [] 
    }; 

非常感谢你的帮助!