无论类型是否正确,PropTypes 都会给出错误

PropTypes giving error no matter if the type is right

我将 React 与 PropTypes 和钩子一起使用

"prop-types": "^15.7.2",

"react": "^16.11.0",

我有一个组件可以从数据库接收一个包含一些数据的对象。然后,测试数据:

{ console.log('Carousel reciving: ', typeof informations, informations) }

给出以下控制台日志:

Carousel reciving:  object (12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

数据通过调用发送到组件:

<Carousel informations={informations} isLoading={isLoading} />

和组件:

const Carousel = ({ informations, isLoading }) => (
    <ReactPlaceholder ...some props />...some content</ReactPlaceholder>
) // Carousel

但是无论我把PropType改成array还是object,还是会报如下错误:

Warning: Failed prop type: Invalid prop informations of type array supplied to Carousel, expected object.

如果我改成PropType.object.isRequired,错误说提供的值是数组类型。如果我更改为 PropType.array.isRequired,则错误提示提供的值是对象类型:

Carousel.propTypes = {
    informations: PropTypes.object.isRequired,
    isLoading: PropTypes.bool.isRequired,
} // propTypes

我知道我可以在组件内部使用 fetch 函数,但此数据与其他组件共享。

从你的console.log来看,informations实际上是一个对象数组;它记录为 [{…}, {…}, 注意开头 [

所以您想将 propTypes 更改为

Carousel.propTypes = {
    informations: PropTypes.arrayOf(PropTypes.object).isRequired,
    isLoading: PropTypes.bool.isRequired,
}