如何在react redux工具包RTK中放置动态类别?

dohp0rv5  于 2022-11-12  发布在  React
关注(0)|答案(1)|浏览(121)

**错误是无法读取未定义的属性(阅读“category”)**我想在产品详细信息页面上匹配我的类别。但我无法实现它。我无法获得类别我尝试了很多方法。请帮助我如何才能做到这一点。
**Redux says**数据:返回来自服务器的实际响应内容。在收到响应之前,此字段将处于未定义状态。

那么我们如何获取数据呢?🤔

注:我使用Redux工具包和RTK查询

我想在我的matchCategory状态中设置我的类别块,默认情况下,当用户单击主页产品按钮(如**“查看详细信息”**)时,该类别块为空。我想匹配此ID类别,并获取所有产品以匹配详细信息类别。

更多详细信息

记住我有一个网站我的网站有20个产品每个产品都有两个按钮一个是添加到购物车另一个是查看详细信息例如您是一个用户,您希望在购买产品之前查看产品详细信息。这里是要点我想显示一个部分,匹配您的产品ID类别,如电子产品。您可以称之为相关产品部分:)
"我该怎么做"

我的产品详细信息页面

import React, { useEffect, useState } from "react";

import {
  useGetSingleProductQuery,
  useGetRelatedProductQuery,
  useGetAllProductsQuery,
} from "../../features/productsApi";

import { useParams } from "react-router-dom";
import axios from "axios";

function ProductDetails() {
  const { id } = useParams();

  const {
    data: getSingleProduct,
    isFetching,
    error,
  } = useGetSingleProductQuery(id);

// Here I can't access category
 const [matchCategory, setMatchCategory] = useState(getSingleProduct?.category);

  const url = `http://localhost:5000/products?category=${matchCategory}`;

  useEffect(() => {
    axios
      .get(url)
      .then((res) => {
        console.log(res.data)
        setMatchCategory(res.data)
      })
      .catch((err) => console.log(err));
  }, []);

  return (
    <div className="row mt-5">
      {isFetching ? (
        <p>Loading ...</p>
      ) : error ? (
        <p>Error occured</p>
      ) : (
        <>
          <div className="col-md-6 mb-5 text-center">
            <img
              className="w-100"
              style={{ height: "300px", objectFit: "contain" }}
              src={getSingleProduct.image}
              alt=""
            />
            <div>{getSingleProduct.title.substring(0, 20)}</div>
            <p>{getSingleProduct.description}</p>
             // But here we access in jsx :( how ?
            <p>{getSingleProduct.category}</p>
          </div>
        </>
      )}
    </div>
  );
}

export default ProductDetails;
vlf7wbxs

vlf7wbxs1#

我认为data对象在第一次是undefined,因此您需要添加一个回退或添加?,如下所示:

const [matchCategory, setMatchCategory] = useState(getSingleProduct?.category);
// or const [matchCategory, setMatchCategory] = useState(getSingleProduct.category ?? {});

相关问题