在use中获取数据使用redux中的action效果

时间:2020-01-31 18:56:24

标签: javascript reactjs redux react-hooks

我试图在useEffect中获取数据,但是每次当我尝试将其作为道具发送到另一个组件(产品)时都得到一个空数组

ProducList.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);

还有我的Product.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>;
};

我需要获取数据并发送到产品组件

1 个答案:

答案 0 :(得分:3)

您的数据似乎从未传递到ProductList组件中(在ProductList中没有对数据道具的引用)。

我相信您正在尝试将产品数据传递到“产品”组件中。这就是您可以做的。

const [newProducts, setNewPropducts] = useState([]);

//add this useEffect and keep your other one
useEffect(() => {
  //set state for products here
  setProducts(products)
}, [products]);


<Product products={newProducts} />