【问题标题】:Extending props with the withRouter HOC in Next.js在 Next.js 中使用 withRouter HOC 扩展 props
【发布时间】:2018-11-17 03:40:59
【问题描述】:

我正在尝试在 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

我认为 flow 会发现 router 是由 withRouter 注入的,但似乎不是这样?如何修复这种类型的错误?

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

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

【问题讨论】:

  • 我不是这里的专家,希望你能听到真正知道这是如何工作的人的意见,但通常在我处理过这种道具注入的地方,我仍然必须定义注入的道具在我用于组件道具的流类型中。
  • 你知道如何从 flow-typed/npm/next_v7.x.x.js 导入路由器类型吗?
  • 我已经通过声明额外的道具更新了问题,但我现在在他的呼叫站点仍然遇到不同的错误

标签: javascript flowtype next.js


【解决方案1】:

好的,我想我明白了。

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

这样就通过了flowtype检查,在调用点不传入Router就可以使用组件了。

【讨论】:

  • 注意:虽然这打破了更漂亮的标准.. 更漂亮的标准以不正确的方式重新格式化代码。但这是一个单独的问题..
  • 其实!我仍然得到 [flow] 无法创建 Post 元素,因为属性 router 在道具 [1] 中缺失,但存在于 Props [2] 中。 (参考文献:[1] [2])
  • 更新了答案以解决上一条评论中提到的问题。
  • 我不明白。为什么知道 Next JS 官方文档中提到了这一点?
【解决方案2】:

尝试将withRouter的类型调整为:

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

并且在您的组件文件中,您必须使用外部 props 转换增强基础组件的结果,现在我只是放置一个空对象。

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


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

【讨论】:

    猜你喜欢
    • 2020-01-10
    • 2019-11-14
    • 2019-01-07
    • 1970-01-01
    • 2019-07-09
    • 2021-03-23
    • 2021-09-22
    • 1970-01-01
    • 2020-01-26
    相关资源
    最近更新 更多