键为 ID 的对象的 PropType
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 以匹配新结构?
见here
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.
}
}
或者您可以使用其他一些检查,例如:字符串长度、mongoose 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,
我正在将我的 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 以匹配新结构?
见here
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.
}
}
或者您可以使用其他一些检查,例如:字符串长度、mongoose 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,