在React.Component道具中脱节联合

时间:2018-05-17 13:22:59

标签: reactjs flowtype

我最近偶然发现了来自flow-js(https://flow.org/en/docs/types/unions/#disjoint-unions-)的disjoint unions,并尝试在我的React.Component道具中使用它们。

基本的想法是我有一套总是需要设置的道具,根据属性,其他一些领域也需要有内容。

在我的示例中,我想要一个isEditable标记 - 如果它是真的 - 还需要设置字段uploadUrl。如果isEditable为false,则uploadUrl必须为null。

// Base properties
type OverallProps = { imageUrl: string, username: string };

// Disjoint unions
type IsPlainProps = { isEditable: false, uploadUrl: null };
type IsEditableProps = { isEditable: true, uploadUrl: string };

// My Props
type Props = OverallProps & (IsPlainProps | IsEditableProps);

不幸的是,我无法使用此设置并且我不知道为什么。

我将场景分离到这个小片段: https://flow.org/try/#0JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwBQdMAnmFnAPIBuWUyANnwAKxMOgC8cAN504cUMgDmWAKpQ+ALjioYUYADsFAGhlwArqh57kILJu26DxgL71GLNgElUgvsn3CIUTgJaVlgVABRABNgGGQAIz5bOAJ+C2NZUzA+CGQo1Q04PVMBZ1dmVjgvaNiEpICgkJNwmrjE5J1TLAyzbNz8tTsdfSM6FwYKtgbxDm5eAWm4ADI4AAovHz89RYAfKsiYtvqRVABKV1xfVHQAZRIsGAALEbgsAA8YLD0o9Gw8GAAdIJTJQAMIkSB6L4wAA80wAfFIxgxcBA9No5Adau1NPEIBA+ME4J0sK4YXcbE8Xs0QIoVGoxAAiBK4RkmcyWaxYJkcqBWGxssJYo7cyQtQ51LBOdl9PIFMRi4WSuAAfjgjKyOTlakZcE0xQE0oA9PCgA

有人可以向我解释为什么我会收到以下错误吗?

<Something 
^ Cannot create `Something` element because: Either boolean [1] is incompatible with boolean literal `false` [2] in property `isEditable`. Or boolean [1] is incompatible with boolean literal `true` [3] in property `isEditable`.

References:
23: const isEditable: bool = true;
                      ^ [1]
9:   isEditable: false,
                 ^ [2]
14:   isEditable: true,
                  ^ [3]

提前非常感谢!

1 个答案:

答案 0 :(得分:0)

您会收到此错误,因为true和false是值。

您正在定义数据类型,例如这样做:

import * as React from 'react';

type OverallProps = {
  imageUrl: string,
  username: string,
};

type IsPlainProps = {
  isEditable: bool,
  uploadUrl: ?string,
};

type IsEditableProps = {
  isEditable: bool,
  uploadUrl: string,
};

type Props = OverallProps & (IsPlainProps | IsEditableProps);

class Something extends React.PureComponent<Props> {
}

const isEditable: bool = true;

<Something 
  imageUrl="abc"
  username="username"
  isEditable={isEditable}
  uploadUrl={isEditable ? "uploadUrl" : null}
/>

您还在为这个问题苦苦挣扎吗?要根据给定的值更改数据结构的类型,也许铸造是正确的解决方案? https://flow.org/en/docs/types/casting/