【发布时间】:2018-04-20 11:12:52
【问题描述】:
我有一些包含不同服装项目的多维 JSON 数据,每个服装项目都包含自己的信息数组。
我正在尝试使用 ReactJS 来显示它:
{Product Name}
{size 1} has {quantity 1} in stock
{size 2} has {quantity 2} in stock
{size 3} has {quantity 3} in stock
我的 JSON 如下所示:
{
"myShirt": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 0,
},
],
"myShirt2": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 0,
},
],
"myShirt3": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 0,
},
]
}
例如,在这种情况下,我想要的输出是:
myShirt
Small has 0 in stock
Medium has 0 in stock
Large has 0 in stock
myShirt2
Small has 0 in stock
Medium has 0 in stock
Large has 0 in stock
myShirt3
Small has 0 in stock
Medium has 0 in stock
Large has 0 in stock
我创建了一个 React 组件,其中包含此 JSON 数据作为其状态的一部分。该组件如下所示:
class Products extends React.Component {
constructor() {
super();
this.state = {
data: [
{
"myShirt": [
{
"size_text": "Small",
"quantity": 0,
},
{
"size_text": "Medium",
"quantity": 0,
},
{
"size_text": "Large",
"quantity": 0,
},
],
"myShirt2": [
{
"size_text": "Small",
"quantity": 3,
},
{
"size_text": "Medium",
"quantity": 0,
},
{
"size_text": "Large",
"quantity": 0,
},
],
"myShirt3": [
{
"size_text": "Small",
"quantity": 3,
},
{
"size_text": "Medium",
"quantity": 0,
},
{
"size_text": "Large",
"quantity": 0,
},
]
}]
}
}
render() {
return (
<div>
{
// HOW DO I DISPLAY MY OUTPUT HERE?
}
</div>
);
}
}
我显示输出的方法是使用 .map。但是,我用来执行此操作的裸代码并不成功。它看起来像这样:
render() {
return (
<div>
{
this.state.data.map((product, i) =>
<p>{product.map((productData, j) =>
<span>{productData.size_text}</span>
)
}</p>
)
}
</div>
);
}
此代码不会尝试显示整个输出,因为我只是在测试水域以查看是否可以得到任何东西,至少是要显示的大小。如您所知,我几乎陷入了组件的渲染功能中。我不知道如何访问产品名称,以及产品尺寸名称和数量。
您将如何解决这个问题以使其看起来像所需的输出?
谢谢!
【问题讨论】:
-
您的 json 似乎不正确。它是一个数组内的集合。它应该是两者之一。地图适用于数组,至于收集,您需要采用不同的方法。
-
@user2030942 请标记this 接受它解决了您的问题
-
@Fawaz 感谢您指出这一点。我已经解决了我的问题。
标签: javascript json reactjs