【问题标题】:React Router match is undefined using Typescript使用 Typescript 未定义 React Router 匹配
【发布时间】:2020-09-03 10:05:24
【问题描述】:

我正在使用 react 和 TypeScript 做一个简单的电子商务 PoC。问题是我无法将道具传递给产品详细信息页面,也无法访问包含paramsmatch

我的路线页面中有以下内容

const Routes = () => (
    <Router>
        <Switch>
            <Route path="/" exact component={require("../pages/home").default} />
            <Route path="/shop" exact component={require("../pages/shop").default} />
            <Route path="/shop/:name" component={require("../pages/shop/details").default} />
        </Switch>
    </Router>
)

在商店页面我这样称呼Link

<Link to={`/shop/${product.name}`}> 
  <Card 
  ... // A card with product info
   </Card>
 </Link>

最后是details

import React from 'react';
import { match } from 'react-router-dom';
import MainLayout from '../../layout/mainLayout';
import './shop.css';

interface IProduct {
  name: string
}

export const ProductDetail = (matched: match<IProduct>) => {
  console.log(matched); // Undefined

  return (
    <>
    </>
  )
};


export default MainLayout(ProductDetail);

我想访问产品的名称以获取它的所有信息,我应该可以使用match.params.name,但它未定义。

我已经尝试过这个选项 https://medium.com/@bopaiahmd.mca/how-to-pass-props-using-link-and-navlink-in-react-router-v4-75dc1d9507b4 https://www.pluralsight.com/guides/react-router-typescript

【问题讨论】:

    标签: reactjs typescript react-router


    【解决方案1】:

    我觉得你需要withRouter HOC

    interface ProductDetailProps {
      match: {
        params: {
          name: string
        }
      }
    }
    
    export const ProductDetail: React.FC<RouteComponentProps<ProductDetailProps>> = withRouter(({match: {params: {name} = {}} = {}} = {}) => {
      console.log(name); 
    
      return (
        <>
        </>
      )
    });
    

    【讨论】:

    • 真是个救命恩人。我做了一些调整以使其正常工作。 export const ProductDetail: React.FC&lt;RouteComponentProps&lt;ProductDetailProps&gt;&gt; = ({ match }) =&gt;保留了只有名字的界面,最后改成了export default MainLayout(withRouter(ProductDetail));非常感谢!
    猜你喜欢
    • 2019-12-14
    • 2021-07-16
    • 2021-06-23
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2016-07-31
    • 2019-12-30
    • 2021-08-11
    相关资源
    最近更新 更多