首页 > 解决方案 > 在 React 中呈现嵌套 json 列表的任何有效方法?

问题描述

我能够获取 REST API 以获取嵌套json输出,并且我希望它们显示在 React 组件中。现在我只能在控制台中渲染它们,这实际上不是我的目标。我想知道是否有一种有效的方法可以json在 React 中呈现嵌套列表。谁能给我一个可能的想法来完成这项工作?

这是我所做的

import React, { Component } from "react";

class JsonItem extends Component {
  render() {
    return <li>
      { this.props.name }
      { this.props.children }
    </li>
  }
}

export default class List extends Component {
  constructor(props){
    super(props)
    this.state = {
    data: []
    }
  };   
  componentDidMount() {
      fetch("/students")
      .then(res => res.json())
      .then(json => {
          this.setState({
          data: json
          });
      });
  }
  list(data) {
    const children = (items) => {
      if (items) {
        return <ul>{ this.list(items) }</ul>
      }
    }
    return data.map((node, index) => {
      return <JsonItem key={ node.id } name={ node.name }>
        { children(node.items) }
      </JsonItem>
    });
  }
  render() {
    return <ul>
      { this.list(this.props.data) }
    </ul>
  }
}
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>

<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

我当前的输出

在我上面的组件中,我可以像这样在控制台上呈现嵌套列表:

[![在此处输入图像描述][1]][1]

所需的输出

如何json在 React 上正确渲染嵌套输出?有什么想法可以实现吗?任何想法?谢谢

标签: javascriptjsonreactjs

解决方案


如您所知.map(),这是常见的解决方案。但是你可以像下面这样做得更好。

export default class List extends Component {
  constructor(props){
    super(props)
    this.state = {
      data: [],
      isLoaded: false,   //initally the loading state is false.
    }
  };

  componentDidMount() {
      fetch("/students")
      .then(res => res.json())
      .then(json => {
          //updating the loading state and data. 
          this.setState({data: json, isLoaded:true}); 
      });
  }

  render() {
   //Waiting ajax response or ajax not yet triggered.  
   if(!this.state.isLoaded){
     return(<div>Loading...</div>);
     }else{
       //Rendering the data from state.
       let studenDetails = this.state.data.map((student, i) => {
         let uin = student.uin; 
         let studentInfo = Object.keys(student.studentInfo).map((label, i) => {
         return (
            <div key={i}>
              <span>
               <strong>{label}: </strong>{`${student.studentInfo[label]}`}
              </span>
            </div>
         );
        });
        return (
         <div key={i}>
           <h3>{uin}</h3>
           <p>{studentInfo}</p>
          </div>
        );
       });
      return (<div>{studenDetails}</div>);
     }
    }
   }

希望它会帮助你。


推荐阅读