我有一个React Component
,我试图使用Object.keys()
方法显示数据,然后尝试使用.map()
遍历数据。
这是redux-logger
打印我的数据的方式:
body: {data: [0: {
attributes: {
name: "Text Widget Name",
category: "PreBuild",
description: "Text Widget Description",
"chart-type": "text_widget"
},
type: "widget-templates"
}]}
我想做的是遍历其中一些。这是我的反应成分。
import PropTypes from "prop-types";
import React from "react";
class TextWidget extends React.Component {
render() {
const {
data
} = this.props;
const textData = data;
const textWidgets = Object.keys(textData[0] || [])
.map(key => {
return (
<div key={key.id} className="tile-head">
<div className="title-head-content">
<h3>{key.attributes.name}</h3>
{key.attributes.description}
</div>
</div>
);
});
return (
<div
data={textData}
>
{textWidgets}
</div>
)
}
}
TextWidget.propTypes = {
data: PropTypes.array
};
export default TextWidget;
key.attributes.name
未定义。
答案 0 :(得分:2)
由于您的数据是数组,因此无需直接使用Object.keys
映射数据即可呈现
const textWidgets = (textData || []).map(key => {
return (
<div key={key.id} className="tile-head">
<div className="title-head-content">
<h3>{key.attributes.name}</h3>
{key.attributes.description}
</div>
</div>
);
});
return (
<div
data={textData}
>
{textWidgets}
</div>
)
}
答案 1 :(得分:1)
Object.keys(textData[0])
将为您提供对象
{
attributes: {
name: "Text Widget Name",
category: "PreBuild",
description: "Text Widget Description",
"chart-type": "text_widget"
},
type: "widget-templates"
}
在迭代过程中,示例中的key
将是attributes
和type
。
Object.keys((textData[0] && textData[0].attributes) || [])
.map(key => {
return (
<div key={key.id} className="tile-head">
<div className="title-head-content">
<h3>{key.name}</h3>
{key.description}
</div>
</div>
);
});
应该做。另外请注意,key
没有id
属性。
答案 2 :(得分:0)
这是因为Object.keys(textData[0] || [])
返回了两个顶级属性。
key = attributes
key = type
const data = [{
attributes: {
name: "Text Widget Name",
category: "PreBuild",
description: "Text Widget Description",
"chart-type": "text_widget"
},
type: "widget-templates"
}];
const textData = data;
const textWidgets = Object.keys(textData[0] || [])
.map(key => console.log(`key = ${key}`));
您需要更深入一点,并指定.attributes
。
const textWidgets = Object.keys(textData[0].attributes || [])
答案 3 :(得分:0)
Object.keys(textData [0])具有值
["attributes", "type"]
要渲染数据,您必须直接在textData上运行地图。
在您的情况下,它将是:
const textWidgets = textData.map((key, index) => {
return (
<div key={index} className="tile-head">
<div className="title-head-content">
<h3>{key.attributes.name}</h3>
{key.attributes.description}
</div>
</div>
)
});