React Router - 将 Slug 作为道具传递给子组件而不是获取 url 的参数

React Router - passing Slug as a prop to child Component and not getting params of url

我正在传递获取 slug 作为锚标记 'href' 并将其作为 URl 参数传递以进行 API 调用。页面正确路由并根据 slug 进行更改。但是,我没有得到 slug 作为 props 参数。

-在此 ProductList 页面中进行 API 调用时,我没有将那个 slug 作为参数

  import React, { useEffect } from "react";
    import { useDispatch } from "react-redux";
    import { getProductBySlug } from "../../actions";
    import Layout from "../../Components/Layout/Layout";
    
    const ProductListPage = (props) => {
    
      const dispatch = useDispatch();
    
      useEffect(() => {
    
        console.log(props);
        // dispatch(getProductBySlug(props.match.params.slug));
    
      }, [dispatch]);
    
      return <Layout>ProductListPage</Layout>;
    };
    
    export default ProductListPage;

您可能只是错过了 useParams() 钩子调用。

以下是将其实施到您的 ProductList 文件中的方法:

import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import { getProductBySlug } from "../../actions";
import Layout from "../../Components/Layout/Layout";
import { useParams } from 'react-router-dom'; // importing the hook

const ProductListPage = (props) => {

  const dispatch = useDispatch();

let params = useParams(); // calling the hook

  useEffect(() => {

    console.log(props);
    dispatch(getProductBySlug(params.slug)); // you'll be able to use params object this way now (omitting the 'prop.match' prefix).

  }, [dispatch]);

  return <Layout>ProductListPage</Layout>;
};

export default ProductListPage;

关于 useParams 挂钩的 React Router 文档:https://v5.reactrouter.com/web/api/Hooks/useparams