【问题标题】:Flow type not saving static props in HOC流类型不保存 HOC 中的静态道具
【发布时间】: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 &amp;&amp; (await Page.getInitialProps(ctx))应该足够了
  • @soywod 感谢您的帮助!我采纳了您的建议并进行了更改 - 现在弹出这 2 个错误 -> 错误:(50, 55) 流程:调用方法 getInitialProps。无法对未知类型的属性 getInitialProps 调用函数 -- 第二个错误 -> 错误:(50, 90) 流:未知类型的属性 getInitialProps。此类型与 union 不兼容:类Promise 的类型应用 |等待的类型参数T。我认为将 getInitialProps 设置为 Function 就足够了..
  • getInitialProps: Function Function 来自哪里?
  • @soywod - Function 是 es6 的通用 Prop 类型,但不确定它是否与 flow 100% 兼容....

标签: reactjs flowtype higher-order-components


【解决方案1】:

我发现摆脱这个错误的最好方法是检查Page.getInitialProps 是否是一个函数。一个简单的typeof Page.getInitialProps === 'function'try ... catch 为我工作,Flow 很高兴。但我还是不明白为什么会这样:const pageProps = Page.getInitialProps ? (await Page.getInitialProps(ctx)) : await Page.getInitialProps?你不能这样做await Page.getInitialProps,只需将其替换为null{}

【讨论】:

  • 我也是这么想的,但如果我只是传递 FunctionalComponent - getInitialProps 不会抛出错误 - 但现在 HOC 不能将 React 组件作为参数。
  • 是的,你正确的 Page.getInitialProps 没有意义。我正在使用 next.js 并从使用 HOC 的示例中得到它——所以我会看看这是否有什么不同。使用功能检查是个好主意!非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2019-01-17
  • 1970-01-01
  • 2023-03-20
  • 2018-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多