我正在将 React 与 PropTypes 和钩子(Hook)一起使用
"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更改为数组还是对象,它仍然给出以下错误:
Warning: Failed prop type: Invalid prop
informations
of typearray
supplied toCarousel
, expectedobject
.
如果我更改为 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,
}
关于javascript - 无论类型是否正确,PropTypes 都会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59430433/