繁体   English   中英

键是 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 以匹配新结构?

这里

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.
  }
}

或者您可以使用其他一些检查,例如:字符串长度、猫鼬 ob​​jectId 等。

来自 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM