Javascript reactjs渲染中的BFS路径
如何使用以下数据为给定的树实现bfs 并展示其结构Javascript reactjs渲染中的BFS路径,javascript,reactjs,Javascript,Reactjs,如何使用以下数据为给定的树实现bfs 并展示其结构 Parent: - Child1 - Child11 - Child2 我不能在渲染函数中使用任何保留关键字来实现bfs算法 我的代码: import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { newData
Parent:
- Child1
- Child11
- Child2
我不能在渲染函数中使用任何保留关键字来实现bfs算法
我的代码:
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
newData : data,
}
}
render() {
const Emp = ({items}) => (
<div>
{items.map((item,i) => {
return <div>{item.id}</div>
})}
</div>
)
return <div>
<Emp items={this.state.newData} />
</div>
}
}
export default App;
从“React”导入React;
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
新数据:数据,
}
}
render(){
常量Emp=({items})=>(
{items.map((item,i)=>{
返回{item.id}
})}
)
返回
}
}
导出默认应用程序;
我得到23(根)作为输出
如何以bfs方式递归打印其每个子级
在
Emp
中,我无法初始化循环或任何变量,有很多方法可以通过它
您可以制作一个组件(如Emp),如果有子组件,它将递归地呈现自己(参见示例:)
或者你可以用更有趣的方式:用标记元素如“depth”使数组的深度展平
[
{
"id": 23,
"parentid": 0,
"depth": 0
},
{
"id": 20,
"parentid": 23,
"depth": 1
},
{
"id": 62,
"parentid": 20,
"depth": 2
},
{
"id": 92,
"parentid": 62,
"depth": 3
},
{
"id": 31,
"parentid": 23,
"depth": 1
}
]
然后用平面.map()
显示它
采取完成功能,使材料:
function flatter(data) {
let depth = 0;
let result = data;
// make this instead if you don't want to mutate the data
// let result = JSON.parse(JSON.stringify(data));
let goDeeper = false;
do {
goDeeper = false;
result = result.reduce(
(acc, { children, ...el }) => {
if (Array.isArray(children) && children.length > 0) {
goDeeper = true;
return acc.concat({ ...el, depth }, children);
}
if (el.hasOwnProperty('depth')) return acc.concat({ ...el });
return acc.concat({ ...el, depth });
},
[]
);
depth += 1;
} while(goDeeper);
return result;
}
function flatter(data) {
let depth = 0;
let result = data;
// make this instead if you don't want to mutate the data
// let result = JSON.parse(JSON.stringify(data));
let goDeeper = false;
do {
goDeeper = false;
result = result.reduce(
(acc, { children, ...el }) => {
if (Array.isArray(children) && children.length > 0) {
goDeeper = true;
return acc.concat({ ...el, depth }, children);
}
if (el.hasOwnProperty('depth')) return acc.concat({ ...el });
return acc.concat({ ...el, depth });
},
[]
);
depth += 1;
} while(goDeeper);
return result;
}