我从服务器获取一个包含包含对象的数组的数组: Arrays with objects
这是有关2座建筑物的信息。有2座建筑物,第一座建筑物有2层,第一层有几个房间,第二层有2个翼楼,每个翼楼内部都有几个房间。在第二栋楼里只有几个房间。作为布局,它看起来像这样: scheme
我想用这样的树的形式用对象渲染这个数组。我设法将其渲染为以下状态:result。接下来,我需要渲染嵌套最多的组件,但是遇到了一个问题。 这是我的组件文件:
import React from 'react';
import ReactDOM from 'react-dom';
class Tree extends React.Component {
constructor(props) {
super(props);
this.state = {
buildings: [],
rooms: []
}
}
componentDidMount() {
var buildings = new Scorocode.Query("buildings");
buildings.find().then((finded) => {
let buildings = finded.result;
this.setState({buildings: buildings});
buildings.map(buildings => (
this.setState({rooms: buildings.rooms})
))
console.info(buildings);
});
}
render() {
return (
<div id="multi-derevo">
<h4><a href="#">Начальная схема</a></h4>
<ul>
{this.state.buildings.map(buildings => (
<li key={this.state.buildings.name}><span><a>{buildings.name}</a></span>
<ul>
{buildings.rooms.map((room, name) => (
<li key={buildings.rooms.name}><span><a>{room.name}</a></span>
<ul>
{rooms.children.map((child, name) => (
<li key={rooms.children.name}><span><a>{child.name}</a></span></li>
))}
</ul>
</li>
))}
</ul>
</li>
))}
</ul>
</div>
);
}
}
export default Tree;
对于最嵌套的组件,我收到一个错误“未定义房间”。据我了解,我需要将其添加到状态中,并且在这里做错了:
buildings.map(buildings => (
this.setState({rooms: buildings.rooms})
))
我是React的新手,所以请不要严格地评判我。我试图寻找解决方案数小时,但仍然无法解决此问题。
答案 0 :(得分:0)
也许这行得通吗?虽然还没有测试
class Tree extends React.Component {
constructor(props) {
super(props);
this.state = {
areas: [],
}
}
componentDidMount() {
var areas = new Scorocode.Query("buildings");
this.setState({ areas })
}
render() {
return (
<ul>
{this.props.parent && <span>{this.props.parent.name}</span>}
{this.state.areas.map((area, i) => {
<li key={i}><Tree parent={area} /></li>
})}
</ul>
)
}
}
export Tree;