我正在尝试根据Java中的rest请求从充满数组的对象创建多维列表。问题是我有能力遍历一系列对象。有人可以给我一个例子,说明如何将该数据结构转换为JSX组件吗?
我正在尝试创建一个包装在div中的列表,如下所示:
<div>
<lo>
<li>
<ul>
<li>Row Cell</li>
<li>Row Cell</li>
</ul>
</li>
<li>
<ul>
<li>Row Cell</li>
<li>Row Cell</li>
</ul>
</li>
</lo>
</div>
在React组件中设置的功能如下
createBodyDisplay(){
var ar = this.state.data.request.body;
var returnString = '';
for (var key in ar) {
console.log(ar);
if (ar.hasOwnProperty(key)) {
if(ar instanceof Array){
console.log('This is a test to see if there is an array');
} else if (ar instanceof Object){
for (var key1 in ar) {
if (ar.hasOwnProperty(key1)) {
console.log(ar[key1]);
}
}
console.log(ar);
} else {
console.log('Not sure what this is');
}
// returnString= returnString+'<div>';
/// var x = numbers.map(Math.sqrt)
// console.log(ar[key]);
// returnString= returnString+'</div>';
}
}
// console.log(returnString);
return returnString;
}
答案 0 :(得分:2)
有关实时示例,请参见此处的沙箱:https://codesandbox.io/s/confident-heyrovsky-s0zg4
假设您的数据结构类似于:
const newData = {
dogs: [
{ type: "row-cell", value: "Golden" },
{ type: "row-cell", value: "Husky" }
],
cats: [
{ type: "row-cell", value: "Feline" },
{ type: "row-cell", value: "Hairless" }
]
};
我们可以使用Object.entries()
为每个键值对创建一个干净的数组。然后使用.map()
创建我们的外部排序列表项目。在每个组中,我们将使用另一个.map()
来创建无序列表项。
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
state = {
data: {}
};
componentDidMount() {
const newData = {
dogs: [
{ type: "row-cell", value: "Golden" },
{ type: "row-cell", value: "Husky" }
],
cats: [
{ type: "row-cell", value: "Feline" },
{ type: "row-cell", value: "Hairless" }
]
};
this.setState({
data: newData
});
}
createNestedLists = () => {
const { data } = this.state;
const lists = Object.entries(data).map(([type, arr]) => {
return (
<li>
<ul>
{arr.map(item => {
return (
<li>
{item.type} - {item.value}
</li>
);
})}
</ul>
</li>
);
});
return <ol>{lists}</ol>;
};
render() {
return <div>{this.createNestedLists()}</div>;
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);