简体   繁体   English

键是 ID 的对象的 PropType

[英]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 以匹配新结构?

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

Or you can use some other checking like: string length, mongoose objectId, etc.或者您可以使用其他一些检查,例如:字符串长度、猫鼬 ob​​jectId 等。

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.

相关问题 使用PropType对嵌套对象属性进行类型检查 - Typechecking nested object properties with PropType 在前端angularjs应用程序中存储密钥和应用程序ID的位置 - where to store the secret keys and app ids in front end angularjs app 如何使用已由另一个 propType 接口定义的动态键和值来验证 propType 形状? - How can I validate a propType shape with dynamic keys and values already defined by another propType interface? 将对象用作 PropType 有什么问题? - What's wrong with using object as a PropType? 如何将模型对象数组转换为以模型 ID 为键的对象? - How to convert array of model objects to object with model ids as keys? 将对象键添加到对象,其中键命名为增量 - Add Object Keys To Object Where keys Named Incremental 从键包含 '.' 的对象创建 json - Create json from object where keys contain '.' 尝试组合两个对象键 ID 匹配的数据集 - Trying to combine two datasets where object key ids match 警告:propType失败:使用React的类型为`array` expected`object`的prop - Warning: Failed propType: Invalid prop of type `array` expected `object` with React React native Undefined不是对象(评估'_react3.default.PropType.shape') - React native Undefined is not an object(evaluating'_react3.default.PropType.shape')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM