[英]PropType for Object Where Keys are IDs
我正在將我的 redux 存儲重構為鍵是 ID 而不是數組的對象。 例子:
老的:
const orders = [
{ id: a, user: 1, items: ['apple','orange'] },
];
新的:
const orders = {
a: { user: 1, items: ['apple','orange'] },
};
以前為訂單指定 PropTypes 很容易,但現在不知道如何更改它,因為它是動態鍵的對象,但我想驗證每個單獨的訂單。
order: PropTypes.arrayOf({
PropTypes.shape({
id: PropTypes.string.isRequired,
user: PropTypes.number.isRequired,
items: PropTypes.arrayOf(PropTypes.string).isRequired,
}).isRequired,
}).isRequired,
我將如何更改我的 PropTypes 以匹配新結構?
看這里
MyComponent.propTypes = {
order: function(props, propName, componentName) {
if (typeof props[propName] !== 'string') { // check if its ID
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
// add more checks for order.user, order.items, etc.
}
}
或者您可以使用其他一些檢查,例如:字符串長度、貓鼬 objectId 等。
來自 prop-types 文檔
// An object with property values of a certain type
optionalObjectOf: PropTypes.objectOf(PropTypes.number),
所以這應該有效
orders: PropTypes.objectOf(
PropTypes.shape({
user: PropTypes.number.isRequired,
items: PropTypes.arrayOf(PropTypes.string).isRequired,
}).isRequired,
).isRequired,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.