代码之家  ›  专栏  ›  技术社区  ›  JSilv

在渲染组件之前,是否反应属性类型警告?

  •  2
  • JSilv  · 技术社区  · 7 年前

    我有一个组件,它将其他组件包裹起来,并在加载所有必要的数据后有条件地呈现它们。然而,我得到了proptype错误 the prop x is marked as required in component Y but its value is undefined . prop x 是尚未从服务器返回的数据,并且 component Y 是数据返回时将渲染的子组件。

    下面是我所说的一个例子:

    <Wrapper contentLoaded={hasDataLoaded && !!dataThatWillLoad}>
      <ComponentWithData
        dataThatWillLoad={dataThatWillLoad}
        dataThatAlreadyExists={dataThatAlreadyExists}
       />
    </Wrapper>
    

    和我的包装器组件:

    const Wrapper = ({ contentLoaded, children }) => {
      if (contentLoaded) return children;
      return <p>Loading</p>;
    }
    

    这将导致错误 Prop dataThatWillLoad is marked as required in component ComponentWithData but its value is undefined .

    这对我来说似乎很奇怪,因为 ComponentWithData 直到数据返回才被渲染。这与检查proptypes的时间有关吗?这段特定的数据是通过mapStateToProps进入组件的,这可能与此有关吗?

    谢谢

    1 回复  |  直到 7 年前
        1
  •  2
  •   iHowell    7 年前

    按照你写的方式,孩子们总是会被创造出来,导致你的问题。通过无条件地将它们作为子对象添加到包装器组件,React将在将它们添加到子对象属性之前使它们成为子对象。另一种方法是使用组件本身向包装器添加一个道具。您可以在 Route React路由器提供的组件: https://reacttraining.com/react-router/web/api/Route

    使用此设计模式,您应该能够跳过渲染,只在加载道具时渲染组件,不加载道具时加载单独的组件。

    编辑:TLDR:按照您的设置方式 ComponentWithData 组件是在作为子组件提供给包装器之前创建并提供道具的。