【发布时间】:2018-01-01 18:31:36
【问题描述】:
我有一个容器组件,它是带有 children 属性的 props 类型:
type Props = {
children: Array<React.Element<any>> | React.Element<any>,
settings: string | Object
};
Container 可以包含唯一一个或多个 React.Element,这取决于它应该选择正确的操作。
在渲染函数中我有类似的东西:
const children = this.props.children;
if ( _.isArray(children) ) {
return _.map(children, (child, key) => checkListComponent(child, key));
}
else if ( _.isObject(children) ) {
return checkListComponent(children);
}
主要功能是:
const checkListComponent = (child: React.Element<any>, key) => {
return child.props.list
? React.cloneElement(child, key ? { options, key } : { options })
: child;
};
毕竟我在 else if
中遇到了 Flow 错误return checkListComponent(children);
流:数组类型。此类型与预期的 React$Element 参数类型不兼容。
它似乎忽略了 children 道具可能的非数组类型。我找到了issue on Github 关于联合数组和对象类型,但什么都没有。
这种情况有什么解决办法吗?
UPD:
props.settings 也有同样的问题,它可以是从服务器获取设置对象的 API url,也可以是直接设置对象。当我调用 axios.get(settings) (显然之前检查 props.settings 现在是一个字符串)Flow 忽略可能的字符串类型并抱怨 Object 给出而不是细绳。 BUT 在我检查对象类型的设置并设置容器状态时在下一行显示
this.setState({ settings: this.props.settings });
它抱怨给出的是 String 而不是 Object。
这怎么可能,我能用它做什么?我可以但不想有两个不同的设置 API 和对象的道具。对于问题的 props.children 部分来说,这绝对是不可能的。
【问题讨论】:
标签: reactjs flowtype flow-typed