如何处理反应路由器 url 参数和类型脚本

How to deal with react router url params and type script

在 React 路由器中,我正在阅读教程,但尝试使用打字稿并获得此代码

let params = useParams();
let id:string = params.invoiceId
let invoice = getInvoice(parseInt(id, 10));

第二行有错误

TS2322: Type 'string | undefined' is not assignable to type 'string'.   Type 'undefined' is not assignable to type 'string'

如何正确执行此操作以查找和显示发票?此外,如果字符串不是整数,如何重新路由到捕获所有 *。

谢谢, 院长

How do I do this properly to lookup and display the invoice?

invoiceId 路由参数可能未定义并输入为 "string | undefined",因此您的 id 类型应该匹配。

const params = useParams();
const id: string | undefined = params.invoiceId;

由于 id 现在也可能未定义,并且 parseInt 需要字符串类型,您可以:

  1. 使用一个guard-clause:

    const invoice = id && getInvoice(parseInt(id, 10));
    
  2. 或使用 Number 构造函数,它采用可选的 any 类型:

    const invoice = getInvoice(Number(id));
    

Also, how to reroute to the catch all * if the string is not an integer.

如果您想 check/test 首先 id 参数以确保它是一个整数,您可以使用正则表达式仅测试数字字符并发出命令式重定向。

示例:

const navigate = useNavigate();

...

useEffect(() => {
  if (id && /[^\d]/g.test(id)) {
    navigate("/", { replace: true });
  }
}, [id, navigate]);