【问题标题】:How to properly type component props in react-router?如何在 react-router 中正确键入组件道具?
【发布时间】:2020-12-30 15:51:27
【问题描述】:

我有路线

 <Route path="/server_form" exact={true} render={(props) => <ServerForm {...props} />}/>

在代码中我有一个服务器,当我点击一个按钮到我的 ServerForm 时我想传递它

let server = { url: "http://localhost", description: "" }
onClick = {() => {
    history.push({
        pathname: "/server_form",
        state: { ...server },
    })
}}

我尝试使用 react-router 中的 RouteComponentProps 输入道具,但没有运气:

type Server = {
    url: string;
    description: string;
}

interface ServerFormProps extends RouteComponentProps<Server> {

}

export function ServerForm(props: ServerFormProps) {
    console.log(props.location.state!.url);
}

在与 console.log 的行中,我收到以下错误:

Property 'url' does not exist on type '{}'.  TS2339

如何正确输入?

附:我的依赖

{
    "@types/react": "^16.9.49",
    "@types/react-dom": "^16.9.8",
    "@types/react-router-dom": "^5.1.5",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.2.0",
    "typescript": "^4.0.2",
}

【问题讨论】:

  • 您需要为位置状态提供通用类型,参见例如stackoverflow.com/a/59857898/3001761
  • @jonrsharpe 解决了组件的问题,但是我如何在 Route 中输入我的渲染函数呢?
  • 您遇到过具体问题吗?什么错误信息,你研究过吗?
  • @jonrsharpe 所以问题是渲染函数不支持重载 RouteComponentProps 的所有 3 个泛型,因为它的签名是 render?: (props: RouteComponentProps&lt;any&gt;) =&gt; React.ReactNode;。所以我无法正常在函数中传递它。没有渲染功能就没有道具
  • 当我以RouteComponentProps&lt;{}, StaticContext, Server&gt; 将类型显式添加到props 或根本不输入时,我收到以下错误:Type 'History&lt;UnknownFacade&gt;' is not assignable to type 'History&lt;Server&gt;'. 这意味着所需的位置泛型没有重载

标签: javascript reactjs typescript react-router


【解决方案1】:

已使用新 API 修复:

let location = useLocation<Server>()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 2018-04-25
    • 2015-09-21
    • 2020-06-06
    • 2022-10-20
    • 2021-07-28
    • 2018-12-14
    相关资源
    最近更新 更多