反应-创建递归子级

时间:2018-12-22 09:02:31

标签: json reactjs recursion tree children

我的问题很简单,我想递归地从json列出一个列表。 我现在所拥有的:

const jsonMenuConfig =[
            {
                main:"Li1",
                inside:[]
            },
            {
                main:"Li2",
                inside:[]
            },
            {
                main:"Li3",
                inside:[{main:"insideLi1",inside:[]},{main:"insideLi2",inside:[]},{main:"insideLi3",inside:[]}]
            }
        ];


class App extends React.Component{
  render(){
    return(
      <ListMaker tree={jsonMenuConfig}/>
    );
  }
}
function ListMaker(props){
  return props.tree !== undefined || props.tree.length > 0 ? 
          <ul>{
            props.tree.map((item)=>{
              return <li>{
                  item.main
                }{
                  <ListMaker tree={item.inside}/>
                }</li>
            })
          }</ul>
        : null
}
ReactDOM.render(
  <App/>,
  document.getElementById('app')
);

我的主要想法是创建可以调用自身的函数,并仅在存在子代时返回更深的子代。 我认为应该可以,但我无法摆脱ul里所有ul的东西。看来ul永远不要在第一和第二个li内渲染,因为它不合适。

props.tree !== undefined || props.tree.length > 0

现在正在发生什么:

<ul>
  <li>
    <ul></ul> -- empty, should never return
  </li>
  <li>
    <ul></ul> -- empty, should never return
  </li>
  <li>
    <ul></ul> ... -- children here, succes
  </li>
</ul>

我只是想要的东西:

<ul>
  <li></li>
  <li></li>
  <li>
    <ul>
      <li></li> ... -- children here, succes
    </ul>
  </li>
</ul>

有什么可能是错误的? 可以做得更好吗?

1 个答案:

答案 0 :(得分:1)

这里的逻辑不好。将fit('Should test observable with store', fakeAsync(() => { const testData = [1, 2, 3, 4]; let index = 0; myObservable.subscribe(t => { expect(t).toBe(testData[index]); }); testData.forEach(td => { myStore.set(td) tick(100); index++; }); })); 更改为props.tree !== undefined || props.tree.length > 0

props.tree !== undefined && props.tree.length > 0的意思是||,因此,如果任一条件为true,则它将求值为true,并且由于定义了or,因此它为true。