从 react-router-dom 属性“sumParams"升级版本 4 useParams() 后 TypeScript 错误在类型“{}"上不存在 [英] TypeScript error after upgrading version 4 useParams () from react-router-dom Property 'sumParams' does not exist on type '{}'

查看:153
本文介绍了从 react-router-dom 属性“sumParams"升级版本 4 useParams() 后 TypeScript 错误在类型“{}"上不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

升级到版本 4 后出现 typeScript 错误在react-router-dom的useParams()中使用

I get a typeScript error after upgrading to version 4 Used in useParams () from react-router-dom

打字稿":^4.0.2"

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

const { sumParams } = useParams();

Property 'sumParams' does not exist on type '{}'. 

项目运行良好,只有在升级后才抛出错误

The project worked great and only after the upgrade does it throw an error

推荐答案

useParams 是通用的.您需要通过指定泛型的值来告诉打字稿您正在使用哪些参数

useParams is generic. You need to tell typescript which params you are using by specifying the value of the generic

有几种方法可以解决这个问题

There are several ways to solve this

这是我最喜欢的方式

const { sumParams } = useParams<{ sumParams: string }>();

但是还有一些方法(:

interface ParamTypes {
  sumParams: string;
}

然后在你的组件中

const { sumParams } = useParams<ParamTypes>();

添加任何没有接口的类型

add any type without interface

const { sumParams } : any = useParams();

注意:这样你将无法将其设置为字符串

Note: that this way you will not be able to set it as a string

keemor的更多选项:

const { sumParams } = useParams() as { 
  sumParams: string;
}

这篇关于从 react-router-dom 属性“sumParams"升级版本 4 useParams() 后 TypeScript 错误在类型“{}"上不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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