[英]How can I destructure a JSON response into a table?
I am creating a functional component am fetching some data from an internal API and am wondering how I can make destructure the table rows into something a little less verbose.我正在创建一个功能组件,从内部 API 获取一些数据,并且想知道如何将表行解构为不那么冗长的东西。 The following is the response I am getting from this API.
以下是我从这个 API 得到的响应。
{
"data": [
{
"id": "cc134653-c463-4e79-8b9e-f52dfe02498e",
"type": "bottle",
"attributes": {
"name": "Luc Belaire Rare Luxe",
"price": "$29.99",
"image": "https://cdn11.bigcommerce.com/s-
7a906/images/stencil/1000x1000/products/10929/10518/Luc-Belaire-Rare-Luxe__73902.1555086630.jpg?c=2",
"sku": "813497005010",
"size": "750ML",
"origination": "France",
"varietal": "Sparkling Wine"
}
},
}
I am setting the state of the component like this.我正在像这样设置组件的 state。
const [bottles, setBottles] = useState([]);
useEffect(() => {
fetch('http://localhost:3000/api/v1/bottles?', { method: "GET" })
.then(response => response.json())
.then(data => setBottles(data.data));
});
This is how I am creating a table body in my component but am wondering if there is a better way to use the bottle.attributes.name
and other attributes to make it more like {name}
.这就是我在组件中创建表格主体的方式,但我想知道是否有更好的方法来使用
bottle.attributes.name
和其他属性使其更像{name}
。 How can I achieve this?我怎样才能做到这一点?
<tbody>
{bottles.map(bottle =>
<tr key={bottle.id}>
<td><img src={bottle.attributes.image} alt={bottle.attributes.name} height={150} width={100}/></td>
<td>{bottle.attributes.name}</td>
<td>{bottle.attributes.sku}</td>
<td>{bottle.attributes.price}</td>
<td>{bottle.attributes.size}</td>
<td>{bottle.attributes.origination}</td>
<td>{bottle.attributes.varietal}</td>
</tr>
)}
</tbody>
It will have to be a bit repetitive regardless - if you destructure the argument, you'll have to list out each individual property in the argument list:无论如何,它都必须有点重复——如果你解构参数,你必须在参数列表中列出每个单独的属性:
{bottles.map(({ id, attributes: { image, name, sku, price, size, origination, varietal }}) =>
<tr key={id}>
<td><img src={image} alt={name} height={150} width={100}/></td>
<td>{name}</td>
<td>{sku}</td>
I'd prefer to just destructure to get the attributes
, and then list attributes.name
, etc:我宁愿只解构以获取
attributes
,然后列出attributes.name
等:
<tbody>
{bottles.map(({ id, attributes }) =>
<tr key={id}>
<td><img src={attributes.image} alt={attributes.name} height={150} width={100}/></td>
<td>{attributes.name}</td>
<td>{attributes.sku}</td>
which is better than going through bottle
each time.这比每次都经过
bottle
要好。
You could make an array of the property names and use an inner map()
您可以制作一个属性名称数组并使用内部
map()
const attrs =['name', 'sku', 'price', 'size', 'origination', 'varietal']
<tbody>
{bottles.map(bottle =>
<tr key={bottle.id}>
<td><img src={bottle.attributes.image} alt={bottle.attributes.name} height={150} width={100}/></td>
{attrs.map(k => <td>{bottle.attributes[k]}</td>}
</tr>
)}
</tbody>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.