Javascript 从数据库中获取数据并通过db列中的数组映射
抱歉,如果滴度有点低或不好 但问题是,我从我的数据库中提取,并使用map来显示每个产品,我在渲染的产品中有一个selectionbox,我试图从数据库中的数组进行映射 我是这样说的:Javascript 从数据库中获取数据并通过db列中的数组映射,javascript,sql,reactjs,Javascript,Sql,Reactjs,抱歉,如果滴度有点低或不好 但问题是,我从我的数据库中提取,并使用map来显示每个产品,我在渲染的产品中有一个selectionbox,我试图从数据库中的数组进行映射 我是这样说的: fetch('/api/products') .then(res => res.json()) .then(allProducts => { this.setState({ allProducts }); }); { this.state.allProducts.map
fetch('/api/products')
.then(res => res.json())
.then(allProducts => {
this.setState({ allProducts });
});
{
this.state.allProducts.map(allProducts =>
<div className="products" key={allProducts.produkt_id}>
<select name="format">
<option value="choose_format">choose format</option>
</select>
</div>
)
}
我的地图是这样的:
fetch('/api/products')
.then(res => res.json())
.then(allProducts => {
this.setState({ allProducts });
});
{
this.state.allProducts.map(allProducts =>
<div className="products" key={allProducts.produkt_id}>
<select name="format">
<option value="choose_format">choose format</option>
</select>
</div>
)
}
{
this.state.allProducts.map(allProducts=>
选择格式
)
}
在my db中,数组按如下方式存储在列中:
[{“汽车”:“奥迪”},{“汽车”:“宝马”}]
我如何把不同的汽车规划成可选的,或者我做错了什么,我能以更好的方式存储它吗
{ produkt_id: "123", car: "bwm" , color: [{"color":"audi"},{"color":"bmw"}]}
然后,您的渲染将是:
return this.state.allProducts.map((product) => (
<div className="products" key={product.produkt_id}>
<select name="format">
{product.color.map((colorOption) => (
<option value={colorOption.color}>{colorOption.color}</option>
))}
</select>
</div>
));
返回this.state.allProducts.map((产品)=>(
{product.color.map((colorOption)=>(
{colorOption.color}
))}
));
{produkt_id:“123”,car:“bwm”,color:[{“color”:“red”},{“color”:“white”}}也许数组中的颜色我可以稍后删除,所以它不必说两遍颜色,但这是一个更好的示例,我现在就有了它,我想要显示汽车每种颜色的选项,我该怎么做?更新以匹配您的数据格式。我正在尝试您的解决方案,但我得到“TypeError:product.color.map不是函数”,您知道为什么吗?告诉您颜色不是数组,因此它没有.map
函数。非常感谢,我使用了JSON.parse(),而不是product.color.map,我不得不使用JSON.parse(product.color.map)