在自定义react钩子中使用axios获取数据不会返回数据

wvmv3b1j  于 2023-01-17  发布在  iOS
关注(0)|答案(1)|浏览(205)

我使用这段代码来显示产品的id

import { useState } from 'react';
import axios from 'axios';

const BASE_URL = "https://makeup-api.herokuapp.com/api/v1/products";

const useGetProduct = () => {
  const [products, setProducts] = useState([]);
  const [singleProduct, setSingleProduct] = useState(null);
    
  const getTopProducts = () => {
    axios.get(`${BASE_URL}.json`, {
      params: {
        product_tags: 'Canadian',
      },
    })
      .then(Response => setProducts(Response.data));
  };

  const getSingleProduct = () => {
    axios.get(`${BASE_URL}/1048.jason`)
      .then(Response => setSingleProduct(Response.data));
  };

  return {
    products,
    getTopProducts,
    singleProduct,
    getSingleProduct,
  }
};

export default useGetProduct;
import React, { useEffect } from "react";
import { useParams } from "react-router-dom";
import useGetProduct from "../hooks/useGetProduct";

const Product = () => {
  const { id } = useParams();
  const { singleProduct, getSingleProduct } = useGetProduct();

  useEffect(() => {
    getSingleProduct();
  }, []);
   
  return ( 
    <div>
      <p>Product: {id}</p>
    </div>
  );
};
 
export default Product;

app.js

<Route exact path="/product/:id" element={<Product />} />

但是当我将<p>Product: {id}</p>更改为<p>Product: {singleProduct?.name}</p>时,产品名称没有显示,而是只显示Product:,而没有localhost上有关产品的详细信息,我不知道为什么。

const Product = () => {
  const { id } = useParams();
  const { singleProduct, getSingleProduct } = useGetProduct();
    
  useEffect(() => {
    getSingleProduct();
  }, []);
   
  return ( 
    <div>
      <p>Product: {singleProduct?.name}</p>
    </div>
  );
};
 
export default Product;

我想通过react js中的一个钩子来展示单个产品的细节。

xmq68pz9

xmq68pz91#

const { id } = useParams();
  const { singleProduct, getSingleProduct } = useGetProduct();

  useEffect(() => {
      getSingleProduct();
  }, []);

您没有使用useParams中的id。您不应该将其传递给getSingleProduct吗?我假设singleProduct未定义。

相关问题