gpt4 book ai didi

javascript - 在 React 中呈现嵌套 json 列表的任何有效方法?

转载 作者:行者123 更新时间:2023-11-30 11:05:32 25 4
gpt4 key购买 nike

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

这是我所做的:

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]

期望的输出:

如何在 React 上正确呈现嵌套的 json 输出?有什么想法可以做到这一点吗?任何想法?谢谢

最佳答案

如您所知,.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>);
}
}
}

希望对你有所帮助。

关于javascript - 在 React 中呈现嵌套 json 列表的任何有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55796827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com