我正在尝试在useEffect中获取数据,但是每次当我尝试将其作为道具发送到另一个组件(产品(时,我都会得到一个空数组
产品列表.js
import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
import { fetchProducts } from "../actions/products";
import { Product } from "./Product";
const ProductList = ({ getProducts, products, loading }) => {
useEffect(() => {
getProducts();
}, []);
return (
<div className="p-4">
<Product products={data} />
</div>
);
};
const mapStateToProps = state => ({
products: state.products,
loading: state.loading
});
const mapDispatchToProps = {
getProducts: fetchProducts
};
export default connect(mapStateToProps, mapDispatchToProps)(ProductList);
这是我的产品.js
import React from "react";
export const Product = props => {
const products = props.products.map(product => {
return (
<div className="col-lg-4 mb-4" key={product.Id}>
<div className="card shadow-sm">
<img
className="card-img-top"
src={`/images/${product.Id}.jpg`}
alt={product.name}
/>
<div className="card-body">
<h5 className="card-title">
{product.name}{" "}
<span className="badge badge-warning">${product.price}</span>
</h5>
<a href="#" className="btn btn-secondary mx-auto">
Add to cart
</a>
</div>
</div>
</div>
);
});
return <div className="row">{products}</div>;
};
我需要获取数据并发送到产品组件
看起来您的数据从未传递到产品列表组件中(产品列表中没有对数据道具的引用(。
我相信您正在尝试将产品数据传递到产品组件中。这是你可以做的。
const [newProducts, setNewPropducts] = useState([]);
//add this useEffect and keep your other one
useEffect(() => {
//set state for products here
setProducts(products)
}, [products]);
<Product products={newProducts} />