在我的react应用程序中,我正在实现一个树形视图结构,以更易读的格式显示api响应。我为此使用树视图反应引导程序。
import React from 'react';
import ReactDOM from 'react-dom';
import TreeView from 'treeview-react-bootstrap'
class Example extends React.Component {
constructor(){
super();
// SET YOUR DATA
this.state = {
data: [
{
text: "John Peter",
nodes: [
{
text: "ID: 11111",
nodes: [
{
text: "VIN"
},
{
text: "Policy Effective Date"
},
{
text: "Policy Expiration Date"
},
{
text: "Vehicle Make"
},
{
text: "Vehicle Model"
}
]
},
{
text: "ID: 123456",
nodes: [
{
text: "VIN"
},
{
text: "Policy Effective Date"
},
{
text: "Policy Expiration Date"
},
{
text: "Vehicle Make"
},
{
text: "Vehicle Model"
}
]
}
]
},
{
text: "Scott Brown"
}
]
}
}
render(){
return (
// RENDER THE COMPONENT
<TreeView data={this.state.data} />
);
}
}
export default Example
我现在正在使用伪数据,但这是我希望显示我的数据的格式。我的api响应是“对象数组”,并且只有一种JSON格式。
示例响应-
[
{
"id": "1234",
"name": "John Scott",
"vin": "45",
"make": "Toyota",
"model": "Etios"
},
{
"id": "4567",
"name": "James Scott",
"vin": "67",
"make": "Hyundai",
"model": "Etios"
}
]
如果看到响应,我希望将键值打印在树形结构中。
有没有一种方法可以渲染此响应以适应treeview-react-bootstrap?
我不确定是否需要在我的render方法中使用map函数来迭代和显示数据以及它如何工作。有人可以让我知道我做得对还是有更好的方法它。预先感谢。
答案 0 :(得分:1)
您可以像这样转换响应。刚刚添加了虚拟响应。请检查以下代码,让我知道是否有帮助:
import React from "react";
import ReactDOM from "react-dom";
import TreeView from "treeview-react-bootstrap";
import axios from "axios";
class Example extends React.Component {
constructor() {
super();
// SET YOUR DATA
this.state = {
data: []
};
}
componentDidMount() {
axios
.get("https://www.mocky.io/v2/5bb85d723000005f00f93bb6")
.then(data => {
let transformedData = data.data.map(d => {
return {
text: d.text,
nodes: [
{
text: "dummy 1",
nodes: []
}
]
};
});
this.setState({ data: transformedData });
});
}
render() {
return (
// RENDER THE COMPONENT
<TreeView data={this.state.data} />
);
}
}
ReactDOM.render(<Example />, document.getElementById("app"));
您还可以在此处查看它的运行情况:https://codesandbox.io/s/73ryny9ywq?autoresize=1&hidenavigation=1