如何使用react和from redux action获取id

pieyvz9o  于 2022-11-24  发布在  React
关注(0)|答案(2)|浏览(124)

我正在使用match.params从后端获取单个产品的ID,但我遇到错误,请帮助我解决此错误

import React, { useEffect } from "react";
import Carousel from "react-material-ui-carousel";
import "./ProductDetail.css";
import { useSelector, useDispatch } from "react-redux";
import { getProductDetails } from "../../actions/productActions";

const ProductDetail = ({ match }) => {
  const dispatch = useDispatch();

  const { product, loading, error } = useSelector(
    (state) => state.productDetail
  );

  useEffect(
    () => {
      dispatch(getProductDetails(match.params.id));
    },
    [dispatch, match.params.id]
  );

我收到此错误:
TypeError:无法读取未定义的属性(阅读'params')

| useEffect(
  15 |   () => {
  16 |     dispatch(getProductDetails(match.params.id));
> 17 |   },
     | ^  18 |   [dispatch, match.params.id]
  19 | );

请提供此问题的解决方案或任何其他解决方法??

ax6ht2ek

ax6ht2ek1#

尝试将空合并运算符添加到match

useEffect(
    () => {
      dispatch(getProductDetails(match?.params?.id));
    },
    [dispatch, match.params.id]
  );

此外,检查代码中是否有paramsidconsole.log(match)的匹配也很有用。

dvtswwa3

dvtswwa32#

假设ProductDetail是一个动态页面,您需要访问参数id。

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

const { id } = useParams();

useEffect(
    () => {
      dispatch(getProductDetails(id));
    },
    [dispatch,id]
  );

相关问题