Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

reactjs - how to validate props as an array of objects?

Here is part of a component where I pass props as an array of objects:

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

<MyComponent myProps={data} /> 

Here is my component where I'm trying to validate props

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

The error I'm getting is:

The prop active is marked as required in MyComponent, but its value is undefined

question from:https://stackoverflow.com/questions/65852156/how-to-validate-props-as-an-array-of-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you are passing down as props myProps.active and status are part of your object shape. With that in mind your propType should look like:

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

also remember to import PropTypes at the top:

import PropTypes from 'prop-types';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...