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

时间:2019-05-24 04:50:13

标签: reactjs typescript react-router react-hooks

我有一个需要利用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"],我没有收到错误,但是由于某种原因,我认为这不是正确的方法。如果有人能指出我正确的方向,我将不胜感激。

3 个答案:

答案 0 :(得分:0)

您可以尝试将默认值赋予const { id } = useReactRouter().match.params || {id: ""};

params

const httpOptions = { headers: new HttpHeaders({ 'Accept': 'application/json', 'Content-Type': 'application/json' }), responseType: 'text' as 'json' } ... search(term:string){ let promise = new Promise((resolve, reject) => { let apiURL = `${this.apiRoot}?term=${term}&media=music&limit=20`; this.http.get(apiURL, httpOptions).toPromise().then(res => { // console.log( res.json() ); resolve(); }, function(error){ console.log('error is', error); }) }); return promise; } 在初始级别可能为空

答案 1 :(得分:0)

代码不足。 但是,乍看之下,

//  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())

答案 2 :(得分:0)

我知道了。解决方案是在钩的名称和括号之间加入尖括号,如下所示:

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

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

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