2016-08-24 47 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: [] 
    }; 

非常感謝你的幫助!