我将redux存储重构为键为ID而非数组的对象。示例:
旧:
const orders = [
{ id: a, user: 1, items: ['apple','orange'] },
];
新:
const orders = {
a: { user: 1, items: ['apple','orange'] },
};
以前很容易为订单指定PropType,但是由于它是动态键的对象,所以现在不知道如何更改它,但是我想验证每个单独的订单。
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.
}
}
或者您可以使用其他一些检查方法,例如:字符串长度,猫鼬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,