REACT:在Recursion的帮助下的JSON树

时间:2017-08-21 06:25:57

标签: javascript reactjs

JSON后端人员为我提供了多个父子,因此我必须将动态循环显示给父子。

JSON

"data": [
  {
    "id": 25,
    "slug": "mobiles",
    "parent_id": null,
    "name": "Mobiles"
  },
  {
    "id": 26,
    "slug": "mobile-phones-accessories",
    "parent_id": 25,
    "name": "Mobile Phones accessories"
  },
  {
    "id": 27,
    "slug": "computer-laptop",
    "parent_id": null,
    "name": "Computer & Laptop"
  },
  {
    "id": 28,
    "slug": "laptops",
    "parent_id": 27,
    "name": "Laptops"
  },
  {
    "id": 29,
    "slug": "mobile-phones",
    "parent_id": 26,
    "name": "Mobiles Phone"
  }
]

我的功能(请忽略这一点。这只是一次尝试,但我有一个孩子的父母)

renderCategoriesHtml() {
  const { categories } = this.props;

  if (!categories) return false;

  const nullCat = [];
  categories.map((obj) => {
    if (obj.parent_id == null) {
      nullCat.push(obj);
    }
  });

  return nullCat.map(
    (parentCat, i) => (
      <div className="form-group" key={i}>
        <div className="checkbox" key={i}>
          <label>
            <Field
              name={`categories.${parentCat.id}`}
              component="input"
              type="checkbox"
            />
            {parentCat.slug}
          </label>
        </div>
        {
          categories.map(
            (childCat, j) => (
              parentCat.id == childCat.parent_id ?
                <div className="checkbox ml-20" key={j}>
                  <label>
                    <Field
                      name={`categories.${childCat.id}`}
                      component="input"
                      type="checkbox"
                    />
                    {childCat.slug}
                  </label>
                </div>
                : ''
            )
          )
        }
      </div>
    )
  );
}

我想要这个(我想要的动态HTML)

<ul>
  <li>mobiles</li>
  <ul>
      <li>mobile-phones-accessories</li>
      <ul>
          <li>mobile-phones</li>
      </ul>
  </ul>            
  <li>computer-laptop</li>
  <ul>
      <li>laptops</li>
  </ul>    
</ul>

1 个答案:

答案 0 :(得分:2)

试试这个:

class TreeRender extends React.Component {
  state = {
    data: JSON.parse('[{"id": 25,"slug": "mobiles","parent_id": null,"name": "Mobiles"},{"id": 26,"slug": "mobile-phones-accessories","parent_id": 25,"name": "Mobile Phones accessories"},{"id": 27,"slug": "computer-laptop","parent_id": null,"name": "Computer & Laptop"},{"id": 28,"slug": "laptops","parent_id": 27,"name": "Laptops"},{"id": 29,"slug": "mobile-phones","parent_id": 26,"name": "Mobiles Phone"}]')
  }
  getCurrent = (node) => this.state.data.filter(cNode => cNode.parent_id == node).map(cNode => (
    <ul key={`node_${cNode.id}`}>
      <li>{cNode.name}</li>
      {this.getCurrent(cNode.id)}
    </ul>
  ))

  render() {
    return (
      <div>
        {this.getCurrent(null)}
      </div>
    );
  }
}

FIDDLE