reactjs - 如何将道具验证为对象数组?
问题描述
这是我将道具作为对象数组传递的组件的一部分:
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
解决方案
你是作为道具传下来的myProps
。active
并且status
是您的对象形状的一部分。考虑到这一点,您的 propType 应如下所示:
MyComponent.propTypes = {
myProps: PropTypes.arrayOf(
PropTypes.shape({
active: PropTypes.bool.isRequired,
status: PropTypes.string
})
)
}
PropTypes
还记得在顶部导入:
import PropTypes from 'prop-types';
推荐阅读
- discord.js - DM 频道中的 awaitMessages
- android - 开始购买流程时,应用程序强制将方向横向更改为纵向
- c++ - 如何像二维数组一样使用 natvis 可视化列顺序矩阵
- c# - 全局错误捕获以防止运行时异常导致程序崩溃
- python - 在 Python 中加速打字自动化
- java - Fragments 在发布应用程序 android 中自动开始重新加载
- c++ - 为什么我从随机数中得到相同的答案?
- sql - 客户列表 IN 和 NOT IN
- linux - 解析 html 元素的内容时,Grep 无法识别的选项“-->”
- python - 如何从python中的交互式shell中打破无限生成器循环