gpt4 book ai didi

reactjs - 是否可以使用 PropTypes 来验证类似 Dictionary 的对象?

转载 作者:行者123 更新时间:2023-12-03 13:29:32 24 4
gpt4 key购买 nike

我需要在我的 reducer 中验证类似字典的对象,但由于我已经在使用 Babel,所以我不想求助于 Typescript 等工具。

以此对象为例:

posts : {
byId : {
"post1" : {
id : "post1",
author : "user1",
body : "......",
comments : ["comment1", "comment2"]
},
"post2" : {
id : "post2",
author : "user2",
body : "......",
comments : ["comment3", "comment4", "comment5"]
}
}
allIds : ["post1", "post2"]
}

如何使用 PropTypes 表达我对 byId 对象的期望?是否可以?如果是这样,怎么办?

最佳答案

如果您无法通过 PropTypes 实现您想要的效果,您可以编写自定义 proptype 检查器' 内置属性类型。

如果您想要 byId 的所有值是具有 id 属性的对象, author , bodycomments ,您可以使用shape , objectOf ,和arrayOf 。如果你想要allIds包括 byId 的所有键您可以编写自定义验证器:

posts: PropTypes.shape({
byId: PropTypes.objectOf(PropTypes.shape({
id: PropTypes.string,
author: PropTypes.string,
body: PropTypes.string,
comments: PropTypes.arrayOf(PropTypes.string)
})),
allIds(props, propName, componentName) {
if(!Object.keys(props.byId).every(postID => props[propName].includes(postID))) {
return new Error('allIds must include all the ids provided to byId!');
}
}
})

上面使用了形状,所以它期望 posts带有键的对象 byIdallIds 。它预计 byId是具有属性 values 的对象 也是具有 id 的形状对象, authorbody是字符串,其中 comments是一个字符串数组。最后,它使用自定义 proptype 验证器来检查 byId 中的每个键是否存在。 (帖子 ID)存在于 allIds 中。如果没有,则抛出错误。但请注意,这不包括 allIds 的情况具有 byIds 中不存在的帖子 ID 。请参阅How to know if two arrays have the same values了解更多解决方案。您可以添加isRequired必要时。

关于reactjs - 是否可以使用 PropTypes 来验证类似 Dictionary 的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44835973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com