【发布时间】:2017-11-27 21:54:51
【问题描述】:
我遇到了一个问题,我可以将一个类或一个功能组件传递到我的 HOC 中。在 HOC 中,我需要访问正在传入的组件上的静态属性(PAGE)。这里的问题是,FLOW 给了我一个错误,说它找不到正在传递给 HOC 的 PAGE 上的静态属性:
Error:(50, 21) Flow: property getInitialProps. Property not found in statics of React$Component.
该错误来自以下代码中的这一行:
const pageProps =
(await Page.getInitialProps) && (await Page.getInitialProps(ctx))
任何帮助将不胜感激 - 我的全部 hoc:
type DefaultProps = {
getInitialProps: (ctx:any) => any
}
type FunctionComponent<P> = (props: P) => ?React.Element<*>;
type ClassComponent<D, P, S> = Class<React.Component<D, P, S>>;
type Component<D, P> = FunctionComponent<P> | ClassComponent<D, P, any>;
export default <D: DefaultProps, P: {}, S: {}> (Page: Component<D, P>, title: string = '') => {
class standardLayout extends React.Component {
static async getInitialProps (ctx) {
// Flow can't read getInitialProps
const pageProps = Page.getInitialProps ? (await Page.getInitialProps(ctx)) : await Page.getInitialProps
return {
...pageProps,
currentUrl: ctx.pathname
}
}
render () {
return (
<div>
<Page {...this.props} />
</div>
)
}
}
return connect()(standardLayout)
}
【问题讨论】:
-
可能是因为
getInitialProps不是属性而是方法。你的(await Page.getInitialProps)真奇怪,你指望到这里来做什么?如果要检查getInitialProps是否存在,那么const pageProps = Page.getInitialProps && (await Page.getInitialProps(ctx))应该足够了 -
@soywod 感谢您的帮助!我采纳了您的建议并进行了更改 - 现在弹出这 2 个错误 -> 错误:(50, 55) 流程:调用方法
getInitialProps。无法对未知类型的属性getInitialProps调用函数 -- 第二个错误 -> 错误:(50, 90) 流:未知类型的属性getInitialProps。此类型与 union 不兼容:类Promise的类型应用 |等待的类型参数T。我认为将 getInitialProps 设置为 Function 就足够了.. -
getInitialProps: FunctionFunction来自哪里? -
@soywod - Function 是 es6 的通用 Prop 类型,但不确定它是否与 flow 100% 兼容....
标签: reactjs flowtype higher-order-components