我正在从后端获取数据并将数据传递给 Product.js。但是卡片不会出现,只有搜索栏会出现。我可以使用 console.log(this.state.products);
在控制台中查看数据。那里有进口。
这是我的 Products.js
文件内容。
import Product from "./Product";
class Products extends Component {
constructor() {
super();
this.state = {
products: [],
searchString: ""
};
}
componentDidMount() {
axios.get("http://localhost:9022/products/getAll").then(res => {
this.setState({ products: res.data });
console.log(this.state.products);
});
}
render() {
return (
<div>
{this.state.products ? (
<div>
<TextField
style={{ padding: 24 }}
id="searchInput"
placeholder="Search for products"
margin="normal"
onChange={this.onSearchInputChange}
/>
<Grid container spacing={24} style={{ padding: 24 }}>
{this.state.products.map(currentProduct => (
<Grid item xs={12} sm={6} lg={4} xl={3}>
<Product products={currentProduct} />
</Grid>
))}
</Grid>
</div>
) : (
"No products found"
)}
</div>
);
}
}
export default Products;
这是我的 Product.js 文件内容。
const Product = props => {
return (
<div>
{props.product ? (
<Card>
<CardContent>
<Typography gutterBottom variant="headline" component="h2">
{props.product.fields.title}
</Typography>
<Typography component="p">{props.product.fields.id}</Typography>
</CardContent>
</Card>
) : null}
</div>
);
};
export default Product;
最佳答案
打错了。它是 props.producs
但不是 props.product
。您正在将 products
作为 Prop 传递给 Product
组件,但作为 props.product
访问,因此您需要使用 props.products 访问它
。试试下面更正的代码
const Product = (props) => {
return(
<div>
{ props.products ? (
<Card>
<CardContent>
<Typography gutterBottom variant="headline" component="h2">
{props.products.title}
</Typography>
<Typography component="p">
{props.products.id}
</Typography>
</CardContent>
</Card>
): null }
</div>
)
}
export default Product;
此外,当您执行 .map 或 .forEach 或 for 循环时,您应该将唯一 ID 作为键添加到循环内的父 jsx 元素。在您的代码中,您需要像下面一样添加唯一性
如果每个 currentProduct 都有唯一的 id,那么就这样做
{ this.state.products.map(currentProduct => (
<Grid key={currentProduct.id} item xs={12} sm={6} lg={4} xl={3}>
<Product products={currentProduct} />
</Grid>
))}
否则添加索引作为键,如下所示
{ this.state.products.map((currentProduct, index) => (
<Grid key={`Key_${index}`} item xs={12} sm={6} lg={4} xl={3}>
<Product products={currentProduct} />
</Grid>
))}
关于javascript - 看不到卡片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52879482/