首页 > 解决方案 > 在 Next.js 中使用 withRouter HOC 扩展 props

问题描述

我正在尝试在 Next.js 库中使用 withRouter HOC 助手。

import { withRouter } from 'next/router'

const MyComponent = withRouter(({ router }) => ())

这给出了一个流错误:

[flow] property `router` is missing in props [1]. (References: [1])

即使我为 Next.js 安装了流类型,并且 withRouter 函数具有以下签名:

withRouter: < T > (Component: React$ComponentType < (T & {
  router: Router
}) > ) => class React$Component

我认为router由 withRouter 注入的 flow 可以解决,但似乎并非如此?如何修复此类型错误?

我尝试导入路由器类型并将其声明为道具:

import { Router } from 'next/router'

type Props = { router: Router }
const MyComponent = withRouter(({ router: Router }: Props) => ())

这消除了错误,但现在我得到了一个不同的错误:

Property router is missing in props [1] but exists in object type [2].

 [1] 61│         {typeof query.post !== 'undefined' && <Post />}

 [2] 29│ const Basic = withRouter(({ router }: { router: Router }) => (

标签: javascriptflowtypenext.js

解决方案


好的,我想我明白了。

withRouter是一个用泛型类型化的函数,用 T 参数化。

流文档中有一个关于泛型的部分:https ://flow.org/en/docs/types/generics/ 。

调用此类函数的一种方法是在调用时传入 T 类型:

import { withRouter } from 'next/router'
import type { Router } from 'next/router'

type Props = {}

type PropsWithRouter = Props & {
  router: Router
}

const MyComponent = withRouter<Props>(({ router }: PropsWithRouter) => ())

这样就通过了流类型检查,并且组件可以在调用站点不传入Router的情况下使用。


推荐阅读