2017-07-25 130 views
1

我目前正在開發中ReactJS自定義組件,可以根據JSON顯示樹:傳遞數據反應組件動態

export default { 
    name: 'Main Node', nodeid: 99,toggled: true, 
    children: [ 
     { name: 'Secondary Node',nodeid: 0, 
      chosen: false,pushed: false,toggled: false, 
      children: [ 
       { name: 'Leaf Node',nodeid: 1,chosen: false, 
        pushed: false, toggled: false, 
        children: [{ 
        name : "child 1", pushed: false, 
        toggled: false, chosen:false 
        }] 
       } 
      ] 
     } 
    ] 
}; 

React Hierarchical Tree 目前,該組件能夠呈現自己,因爲我我從靜態Data.js文件發送JSON,如下圖所示:

import React from 'react'; 
import TreeComponent from 'reusable-components/TreeComponent'; 
import HierarchyJson from './internal/Data'; 

export default function ExampleTreeComponent() { 
    return <TreeComponent hierarchyJson={HierarchyJson} functionMode={4} htmlId="tree1" 
    pushLabelValue="include SubLevel" 
    unpushAlertText="plz choose something" 
    pushAlertText="plz choose something" /> 
} 

我想實現的是我的網頁中具有相同的功能,但是從HTTP調用接收JSON數據。

我是ReactJS的初學者,所以我迷失了。

+0

您可以簡單地將http調用的響應作爲prop,即hierarchyJson傳遞,就像傳遞靜態數據一樣。它會工作。 –

+0

我在做HTTP調用時遇到了麻煩,因爲我的應用程序是一個struts/jsp應用程序。 我可以通過jquery post進行調用,然後從js塊內傳遞該回報作爲道具嗎? 另外...我不能讓構建文件在IE上正常工作,他們一直說TreeComponent是無效的。 –

回答

0

你的樹組件不需要擔心數據來自哪裏,而只是擔心有數據。換句話說,無論是從某個本地文件還是從ajax請求到api的數據都不應該成爲樹組件的關注點。所有你需要的是確保它所需的數據被髮送到它。這是我的意思的一個例子。

class sample extends React.Component { 
    constructor() { 
     this.state = { 
      myData: {} //this is the tree 
     } 
    } 

    componentDidMount() { 
     ajax.request(some end point).then(data => { 
      this.setState({myData: data}); 
     }) 
     //this is where its recomended to make async calls. When the promise resolves 
     //the component will render again due to setState being called 
     //and this time myData will be your data from the api 
     //and now the tree component has what it needs to render the data 
    } 

    render() { 
     <Tree data={myData} /> // 
    } 
} 
+0

如何將HTTP調用傳遞給組件,以便它知道從哪裏檢索數據?我的組件將在應用程序的某些部分重用,因此端點調用需要可配置。 –