如何从使用 Typescript 的 React 钩子返回的对象中解构项目?

How can I desctructure items out of an object that is returned from a React hook using Typescript?

我有一个组件需要利用 React Router 查询参数,我正在使用 use-react-router 挂钩包来访问它们。

这是我想要做的:

import React from "react;
import useReactRouter from "use-react-router";


const Foo = () => {
  const { id } = useReactRouter().match.params;

  return (
    <Bar id={id}/>
  )
}

问题是这会在 VS Code 和编译时引发以下错误: Property 'id' does not exist on type '{}'.ts(2339)

我发现如果我像这样重构我的代码: const id = match.params["id"],我没有收到错误,但出于某种原因我觉得这不是正确的方法。如果有人能指出正确的方向,我将不胜感激。

你可以尝试给params默认值

const { id } = useReactRouter().match.params || {id: ""};

params可能在初始级别为空

代码不足。 然而,乍一看,

//  right way
const { history, location, match } = useReactRouter()

//  in your case
const { match: { params : { id } } } = useReactRouter()

// or
const { match } = useReactRouter()
const { id } = match.params

现在,先尝试安慰值。 另外,请尝试将道具从它的容器传递给功能组件,因为它更合乎逻辑。

从你下面的评论来看,我只能假设你解决了它。另外,建议在使用时处理可能的未定义值。

{ id && id }

然而,第一步应该是安慰它是否有价值,

console.log('value xyz', useReactRouter())

我明白了。解决方案是在钩子的名称和括号之间包含尖括号,如下所示:

const { match } = useRouter<{ id: string }>();
const { id } = useRouter<{ id: string }>();

或者如果您更喜欢嵌套解构:

const { match: { params: id } } = useRouter<{ id: string }>();