免责声明:我是React和ES6的新手,所以请耐心等待!
在FacetGroup s .js中,我定义了一些模式,用于比较各种模块中应用程序中使用的PropTypes。它在这个文件中工作得很好
import React from 'react'
import PropTypes from 'prop-types'
import FacetGroup from './FacetGroup';
/* ... */
const FacetGroups = ({ facets }) => (
<div>
{Object.keys(facets).map( facetName => {
const facet = facets[facetName];
return (
<section key={facetName}>
<header>{facet.displayName}</header>
<FacetGroup group={facet} groupName={facetName} />
</section>
);
})}
</div>
);
const GROUP_PROP_TYPE = PropTypes.shape({
displayName: PropTypes.string.isRequired,
/* ... */
isOpen: PropTypes.bool,
isShowingAll: PropTypes.bool
});
FacetGroups.propTypes = {
facets: PropTypes.objectOf( GROUP_PROP_TYPE ).isRequired /* This works fine */
}
/* ... */
export { GROUP_PROP_TYPE, /* ... */ };
然后,在FacetGroup.js(兄弟文件)中,我导入变量,并在FacetGroup proptype定义中使用它:
import React from 'react'
import PropTypes from 'prop-types'
import { GROUP_PROP_TYPE, /* ... */ } from './FacetGroups';
const FacetGroup = ({ group, groupName }) => (
<span>I am a Facet Group</span>
);
FacetGroup.propTypes = {
group: GROUP_PROP_TYPE.isRequired,
groupName: PropTypes.string.isRequired
}
这在浏览器控制台中给出了运行时错误,其中未定义GROUP_PROP_TYPE
(因此isRequired
失败。
未捕获的TypeError:无法读取属性&#39; isRequired&#39;未定义的
我使用webpackStream和webpack通过gulp运行这个JS文件 - 这是我的配置:
module: {
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['es2015', 'react'],
plugins: ['transform-object-rest-spread']
}
}
]
}
有人可以帮我理解为什么会失败吗?这与评估顺序有关吗?我在浏览器中的调试方式与普通JS中的调试方式有问题,因为它是通过webpack和babel编译的......
答案 0 :(得分:0)
正确定义了FacetGroup
import React from 'react'
import PropTypes from 'prop-types'
import { GROUP_PROP_TYPE, /* ... */ } from './FacetGroups';
/* ... */
const FacetGroups = {
facets: PropTypes.objectOf(GROUP_PROP_TYPE).isRequired /* This works fine */
}
答案 1 :(得分:0)
You should avoid circular dependancies.
Try to define GROUP_PROP_TYPE
in a separate file