javascript - React - Rendering an array of objects using Map
问题描述
I'm trying to render an array of objects using Map
and so far I've only been able to render the first item to the browser.
I figured something's up with my .map function, but I don't know enough about React and JS to pinpoint the problem.
Here's my App.js file:
// import
stuff is here
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: []
};
this.componentWillMount = this.componentWillMount.bind(this);
}
componentWillMount() {
fetch('THE-JSON-URL-IS-HERE')
.then(res => res.json())
.then(data => {
this.setState({ items: data });
});
render() {
const { items } = this.state;
return (
<div className="App">
{ items.map((item, num) => {
return (
<div className="people">
<div className="elem">
<p key={num}>{item.elems}</p>
</div>
<p key={num}><strong>{item.name}</strong></p>
<p key={num}><small>{item.title}</small></p>
<div className="hidden">
<p key={num}><small>{item.email}</small></p>
<p key={num}><small><strong>Office: </strong>{item.office}</small></p>
</div>
{/* <p>{item.manager}</p> */}
</div>
);
})}
</div>
);
}
}
export default App;
And here's a sample of the JSON file:
[
{
"elems": "Pr",
"name": "Abby Langdale",
"title": "President",
"email": "alangdale0@hubpages.com",
"office": "Javanrud",
"manager": [
{
"elems": "Vp",
"name": "Johnnie Mouncey",
"title": "Vice President",
"email": "jmouncey0@cnet.com",
"office": "Canto",
"manager": [
{
"elems": "Vp",
"name": "Concordia Burgwyn",
"title": "VP Quality Control",
"email": "cburgwyn0@dyndns.org",
"office": "Zhoukou",
"manager": [
{
"elems": "En",
"name": "Prissie Sainsberry",
"title": "Web Developer IV",
"email": "psainsberry0@yellowbook.com",
"office": "Tugu",
"manager": null
},
etc. Abby's info is all that I've rendered.
解决方案
首先尝试展平阵列。您需要知道数组将拥有的最大级别数。展平后,您可以使用地图功能:
const flatItems = items.flat(3); // flatten up to 3 levels
items.map((item, num) => {
return ( <render your div> );
}
推荐阅读
- java - 诊断失败的部署
- java - Java 泛型:如何避免类头中的混乱
- python - XGBoost(免费套餐)的 Amazon Sagemaker ResourceLimitExceeded 错误
- encryption - SECNamedCurves.getByName("secp256r1") 在 Android Q 中显示 NoSuchMethod 异常
- c# - 运行已解压缩的控制台应用程序时出现 BadImageFormatException 错误
- r - 在R中的数据框列表中拆分列
- javascript - 使用 webpack 导入 d3 模块的语法
- google-apps-script - 在 Google Script 中压缩 PDF 文件
- javascript - 来自 vuex 的 @click 不适用于 vue 组件
- soapui - 复合项目后 Soap UI Pro 缺少请求