javascript - 在 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 }) => (
解决方案
好的,我想我明白了。
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的情况下使用。
推荐阅读
- android - 启用了 multidex 的 transformDexArchiveWithDexMergerForDebug 错误
- .net - 如何使用匹配的主题输出排序的截止日期?
- ruby - 在实例上调用方法,而不用每次调用的实例名称作为方法前缀
- html - 如何修复不同字体的“后备”权重?
- c# - 过程调用无法通过 ProxySql 工作,错误 MySql.Data.MySqlClient.MySqlException (0x80004005): 表 'mysql.proc' 不存在
- plot - 为什么 Octave 3.8 和 4.x 的情节看起来如此不同?
- arrays - 如何使用 lodash 从对象转换为特定的键值对?
- scala - 在 ScalaFX 中更改散点图绘图点的大小和符号
- python - 使用 xarray 滚动分位数
- c - 有没有办法让链接器从库中提取目标文件的一部分进行链接?