将数据动态传递给React Component

时间:2017-07-25 18:58:47

标签: reactjs https

我目前正在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的初学者,所以我现在迷失了。

1 个答案:

答案 0 :(得分:0)

您的树组件不需要担心数据的来源,而只是担心有数据。换句话说,无论是从某个本地文件获取数据还是从ajax请求获取数据都不应该是树组件的关注点。您需要做的就是确保将所需的数据发送给它。这是我的意思的一个例子。

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} /> //
    }
}