class Array extends React.Component {
constructor() {
super();
this.state = {
newArray: [
{
"Category": "Category1","value": [
{
"Name": "Name1"
},{
"Name": "Name2"
},{
"Name": "Name4"
}
]
},{
"Category": "Category2","value": [
{
"Name": "Name3"
}
]
}
],};
}
render() {
var nestedArray = this.state.newArray.map((title,index) => {
return(
<div key={`nestedArray_${index}`}>
<div key={`category_${title}`}>{title.Category}</div>
</div>
)
})
return (
<div>
<h1>{nestedArray}</h1>
</div>
);
}
}
ReactDOM.render(
<Array />,document.getElementById('root')
);
当前代码的Codepen:https://codepen.io/anon/pen/GePyBa
我现在显示如下:
Category1
Category2
理想情况下,我希望它是:
Category1
Name1
Name2
Name4
Category2
Name3
我已经尝试过寻找答案,但是没有任何实际效果.
我尝试做这样的事情,但是不起作用:
render() {
var innerArray = this.state.newArray.map((values) => {
return {this.state.newArray.value[values].map((name,index) => {
return (
<div key={`value_${name}`}>{name.Name}</div>
)
})}
})
var nestedArray = this.state.newArray.map((title,index) => {
return(
<div key={`nestedArray_${index}`}>
<div key={`category_${title}`}>{title.Category}</div>
{innerArray}
</div>
)
})
return (
<div>
<h1>{nestedArray}</h1>
</div>
);
}
Java和React的新手,非常感谢您的帮助.
最佳答案
您还希望在每个标题对象的每个值数组上使用map来呈现所有Name属性.
原文链接:/js/531240.html例
class App extends React.Component {
state = {
newArray: [
{
Category: "Category1",value: [
{
Name: "Name1"
},{
Name: "Name2"
},{
Name: "Name4"
}
]
},{
Category: "Category2",value: [
{
Name: "Name3"
}
]
}
]
};
render() {
var nestedArray = this.state.newArray.map((title,index) => {
return (
<div key={index}>
<h1>{title.Category}</h1>
{title.value.map((val,index) => (
<div key={index}>{val.Name}</div>
))}
</div>
);
});
return (
<div>
{nestedArray}
</div>
);
}
}
ReactDOM.render(<App />,document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>