带有打字稿的 React 路由器 v5 上所需的 url 参数,可以未定义 [英] required url param on React router v5 with typescript, can be undefined

查看:27
本文介绍了带有打字稿的 React 路由器 v5 上所需的 url 参数,可以未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有 TypeScript 的 react-router v5.1 并具有以下路由配置:

I am using react-router v5.1 with TypeScript and have this route configurations:

<Router basename="/" hashType="slash">
    <Switch>
        <Route path="/token/:tokenName">
            <TokenPage />
        </Route>
    </Switch>
</Router>

我尝试访问组件中的 url 参数(tokenName),使用 useParams 钩子,如下所示:

and I try to access the url param (tokenName) in the component, with useParams hook like so:

const TokenPage: FC<TokenPageProps> = props => {
    const { tokenName } = useParams()
    ...
}

然而,typescript 认为 tokenName 参数可以是未定义的:

However, typescript thinks that tokenName param can be undefined:

这是没有意义的,因为如果 URL 中缺少参数,则 react 路由器将不匹配此路由.

which does not make sense since react router won't match this route if the param is missing in the URL.

在这种情况下我该如何解决打字问题?

How can I fix the typing in that situation?

推荐答案

在这种情况下,您的 TokenPage 代码不知道它正在被 Route 包裹.如果 URL 不包含正确的参数,您的组件将不会被呈现,这是对的.但是 Typescript 并不知道这一点.

In this situation, your TokenPage code is unaware it is being wrapped by a Route. You are right that if the URL does not contain the proper parameters, your component wouldn't be rendered. But Typescript isn't aware of this.

您在那里获得的默认输入是正确的,您应该在使用之前检查该值.

The default typing you got there is proper and you should null check the value before using it.

如果您想覆盖类型,useParams 是通用的并且接受指定返回值类型的类型.

If ever you would want to override the typing, useParams is generic and accepts a type specifying the return value type.

interface ParamTypes {
  tokenName: string
}
const { tokenName } = useParams<ParamTypes>()


编辑 09/29/20

最新打字useParams 已更改.

export function useParams<Params extends { [K in keyof Params]?: string } = {}>(): Params;

如您所见,新的默认值是 {},这并不意味着包含的任何键,但通用约束确实假定值的类型为 string.

As you can see, the new default is {} which will not imply any of the keys contained, but the generic constraints does assume that the values are of type string.

因此,以下行现在将产生 Property 'tokenName' 在类型 '{}' 上不存在. TypeScript 错误.

So the following line would now yield a Property 'tokenName' does not exist on type '{}'. TypeScript error.

const { tokenName } = useParams()

要解决此问题,您可以像第一个示例中那样输入带有已知参数的 useParams,或者像这样输入:

To fix this, either you type the useParams with known parameters like in the first example, or you type it like this:

const { tokenName } = useParams<Record<string, string | undefined>>()

这篇关于带有打字稿的 React 路由器 v5 上所需的 url 参数,可以未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆