[英]PropType for Object Where Keys are IDs
I'm refactoring my redux stores to be objects where the keys are IDs instead of arrays.我正在将我的 redux 存储重构为键是 ID 而不是数组的对象。 Example:
例子:
Old:老的:
const orders = [
{ id: a, user: 1, items: ['apple','orange'] },
];
New:新的:
const orders = {
a: { user: 1, items: ['apple','orange'] },
};
It was easy enough to specify the PropTypes for orders previously, but dunno how to change it now that it's an object of dynamic keys, but I want to validate each individual order.以前为订单指定 PropTypes 很容易,但现在不知道如何更改它,因为它是动态键的对象,但我想验证每个单独的订单。
order: PropTypes.arrayOf({
PropTypes.shape({
id: PropTypes.string.isRequired,
user: PropTypes.number.isRequired,
items: PropTypes.arrayOf(PropTypes.string).isRequired,
}).isRequired,
}).isRequired,
How would I change my PropTypes to match the new structure?我将如何更改我的 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.
}
}
Or you can use some other checking like: string length, mongoose objectId, etc.或者您可以使用其他一些检查,例如:字符串长度、猫鼬 objectId 等。
From prop-types docs来自 prop-types 文档
// An object with property values of a certain type
optionalObjectOf: PropTypes.objectOf(PropTypes.number),
so this should work所以这应该有效
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.