【问题标题】:Cannot get 'x' because property 'x' is missing in undefined无法获取“x”,因为未定义中缺少属性“x”
【发布时间】:2018-10-31 16:34:05
【问题描述】:

我一直在尝试将功能性 React 组件从 PropTypes 转换为 Flow。该组件被赋予一个对象,该对象包含要在该组件中使用的字符串。

以前看起来是这样的:

Component.propTypes = {
  strings: PropTypes.objectOf(PropTypes.string),
}

Component.defaultProps = {
  strings: {
    key_one: "string one",
    key_two: "string two",
  }
}

我已将其转换为:

type Props = {
  strings?: { [string_key: string]: string },
}

const Component = ({ strings }: Props) => (
  // component using 
  // label={strings.key_one}
  // etc
)

Component.defaultProps = {
  strings: {
    key_one: "string one",
    key_two: "string two",
  }
}

这会产生错误:

Cannot get strings.key_one because property key_one is missing in undefined [1].

 [1] strings?: { [string_key: string]: string },

如果我删除[string_key: string]: ?string,除了第一条错误消息之外,它还会产生第二条错误消息:

property key_one is missing in object type [1].

如果我删除可选标记,那么错误就会消失,但我无法提供默认道具 (strings?: { [string_key: string]: string }, -> strings: { [string_key: string]: string },)。

阅读问题似乎可能是由于 refinement invalidation 发生在 JSX 的转换中,此处注明:https://github.com/facebook/flow/issues/6350

任何人都可以进一步阐明,并知道是否有办法解决这个问题?

【问题讨论】:

    标签: reactjs flowtype


    【解决方案1】:

    我相信我已经找到了自己问题的答案。这是不直观的。

    查看帖子https://github.com/facebook/flow/issues/1660

    看起来像:

    你不需要在你的 Props 类型中设置 ... prop ... 可选。流量将 如果您有 foo 的默认属性,请确保 foo 是可选的。

    测试我现有的测试似乎通过了 - 表明指定的默认道具仍然在快照中捕获,即使没有标记?。这可行,但确实减少了 type Props = 本身作为文档的使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-15
      • 2019-07-05
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多