在Next.js中使用withRouter HOC扩展道具

时间:2018-11-16 14:40:29

标签: javascript flowtype next.js

我正在尝试与Next.js库中的Router 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注入的,但事实并非如此吗?如何解决此类型错误?

我尝试导入Router类型并将其声明为prop:

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 }) => (

2 个答案:

答案 0 :(得分:0)

尝试将withRouter的类型调整为此:

withRouter: <T: {}>(
  React$ComponentType<{
    ...$Exact<T>,
    router: Router,
  }>,
) => React$ComponentType<T>

在您的组件文件上,您将必须使用外部props增强基本组件的结果,这是我现在仅放置一个空对象的原因。

const MyComponent = ({ router }) => (/* some jsx */)


export default (withRouter(MyComponent): React$ComponentType<{}>)

答案 1 :(得分:0)

好的,我想我明白了。

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

这将通过流类型检查,并且无需在呼叫站点传递路由器即可使用组件。