首页 > 解决方案 > 如何将道具验证为对象数组?

问题描述

这是我将道具作为对象数组传递的组件的一部分:

const data = [
    {
        active: true,
        status: 'Active'
    },
    {
        active: false,
        status: 'Done'
    }
]

<MyComponent myProps={data} /> 

这是我试图验证道具的组件

import React from 'react'
import { bool, string } from 'prop-types'

const MyComponent = ({ myProps }) => {
    return (
        <div>
            <h1>Hello</h1>
        </div>
    )
}

MyComponent.propTypes = {
    active: bool.isRequired,
    status: string
}

export default MyComponent

我得到的错误是:

该道具active在 中标记为必填MyComponent,但其值为undefined

标签: reactjsreact-props

解决方案


你是作为道具传下来的myPropsactive并且status是您的对象形状的一部分。考虑到这一点,您的 propType 应如下所示:

MyComponent.propTypes = {
  myProps: PropTypes.arrayOf(
    PropTypes.shape({
      active: PropTypes.bool.isRequired,
      status: PropTypes.string
    })
  )
}

PropTypes还记得在顶部导入:

import PropTypes from 'prop-types';

推荐阅读