[英]next.js pass props from HOC to child components getInitialProps
[英]Extending props with the withRouter HOC in Next.js
我正在尝试在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注入的,但事实并非如此吗? 如何解决此类型错误?
我尝试导入路由器类型并将其声明为道具:
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
的类型调整为此:
withRouter: <T: {}>(
React$ComponentType<{
...$Exact<T>,
router: Router,
}>,
) => React$ComponentType<T>
在组件文件上,您必须使用外部props增强基本组件的结果,现在我只是放置一个空对象。
const MyComponent = ({ router }) => (/* some jsx */)
export default (withRouter(MyComponent): React$ComponentType<{}>)
好吧,我想我明白了。
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) => ())
这样就通过了流类型检查,并且可以在不通过呼叫站点的路由器的情况下使用组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.