在呈现组件之前反应 proptypes 警告?

React proptypes warning before component is rendered?

我有一个组件可以包裹其他组件,并在加载所有必要数据后有条件地呈现它们。但是,我遇到了 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 进入组件,这可能与它有关吗?

谢谢!

按照你写的方式,总是会创建 children,导致你的问题。通过无条件地将它们添加为 children 到你的包装器组件,React 将在将它们添加到 children 属性之前创建它们。另一种方法是使用组件本身向包装器添加一个道具。您可以在 React Router 提供的 Route 组件中看到这样的示例:https://reacttraining.com/react-router/web/api/Route

使用这种设计模式,您应该能够通过仅在加载 props 时渲染组件而在未加载时加载单独的组件来跳过渲染。

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