gpt4 book ai didi

javascript - 如何使用 Typescript 从 react-router-dom 访问路由参数?前 : `/some-route/:slug`

转载 作者:行者123 更新时间:2023-12-04 02:32:10 24 4
gpt4 key购买 nike

以这个带有路由参数 slug 的示例路由为例:
路线.ts

export const SOME_ROUTE = `/some-route/:slug`;
还有这个 <Switch>将呈现 <Route> 的组件的。
AllRoutes.tsx
import React from "react";
import * as ROUTES from "@routes/ROUTES";

interface AllRoutes {
}

const AllRoutes: React.FC<AllRoutes> = (props) => {
console.log("Rendering AllRoutes...");

return(
<Switch>
<Route exact path={ROUTES.SOME_ROUTE} component={MyComponent}/>
</Switch>
);
};

export default AllRoutes;
现在从渲染的组件:
我的组件.tsx
import React from "react";
import HomePage from "./HomePage";
import { RouteComponentProps } from "react-router-dom";

interface MyComponent extends RouteComponentProps {
}

const MyComponent: React.FC<MyComponent> = (props) => {
console.log("Rendering MyComponent...");

console.log(props.match.params.slug); // TRYING TO ACCESS THE `:slug` ROUTE PARAM

return(
<HomePage/>
);
};

export default MyComponent;
问题
我收到一条错误消息,指出 slug属性不存在。即使它 100% 存在,因为值会被记录。但 Typescript 并没有意识到这一点。
我是否需要手动扩展 RouteComponentProps添加 props.match.params.slug属性(property)?
enter image description here routeProps ( historymatchlocation )如下图所示。
enter image description here

最佳答案

在评论和其他内容的帮助下:

  • In ReactJS trying to get params but I get property 'id' does not exist on type '{}'
  • 而这篇文章:Using typescript to write react-router 5

  • 这是我的做法:
    import React from "react";
    import HomePage from "./HomePage";
    import { RouteComponentProps } from "react-router-dom";

    interface RouteParams {
    slug: string
    }

    interface MyComponent extends RouteComponentProps<RouteParams> {
    }

    const MyComponent: React.FC<MyComponent> = (props) => {
    console.log("Rendering MyComponent...");

    console.log(props.match.params.slug);

    return(
    <HomePage/>
    );
    };

    export default MyComponent;
    使用参数()
    并且还使用 useParams()钩:
    interface RouteParams {
    slug: string
    }

    const params = useParams<RouteParams>();

    关于javascript - 如何使用 Typescript 从 react-router-dom 访问路由参数?前 : `/some-route/:slug` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63635997/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com