簡體   English   中英

如何使用已由另一個 propType 接口定義的動態鍵和值來驗證 propType 形狀?

[英]How can I validate a propType shape with dynamic keys and values already defined by another propType interface?

假設我為用戶 object有以下道具類型接口:

const userPropType = shape({
  name: string,
  address: string,
  age: number    
});

然后我想驗證一個全局用戶的 object由 props 接收,它由幾個單獨的用戶對象組成,其中鍵是隨機數字 ID。 例如:

{
  3142: {
    name: 'Jonh Doe',
    address: 'Baker Street',
    age: 23 
  },
  4345: {
    name: 'Jane Doe',
    address: 'Fourth Avenue',
    age: 64 
  }
}

我知道我可以使用 Prop Type 自定義驗證器毫無問題地驗證數字鍵。 但問題是:如何使用可以動態驗證密鑰的自定義處理程序以及基於我已經定義的userPropType接口的值來驗證我的全球用戶的 object。

在這個簡短的示例中,我可以輕松地在自定義驗證器上鍵入檢查每個用戶屬性,但如果我們考慮一個真實的案例場景,即我的用戶 object 可能有超過 50 個屬性,自定義驗證每個屬性會很煩人他們,特別是當我已經為我的單個用戶 object 定義了 propType 時。

那么,問題來了:是否可以在自定義驗證器中使用已經定義的 prop-type 接口?

謝謝!

我已經看到這還沒有得到回答。 因為我已經找到了解決方案,所以我在這里分享它,希望它可以對其他開發人員有所幫助。

我已經實現了一個自定義驗證器,它可以檢查道具是否確實符合我期望的格式。

澄清一下,我的“用戶”屬性應該是帶有數字鍵的 object(即使表示為字符串)並具有三個屬性:名稱(字符串)、地址(字符串)和年齡(數字)。

這是我的自定義實現:

const usersObjectPropType = (
  propValue,
  key,
  componentName
) => {
  let isNotValid;
  const userKeys = Object.keys(propValue.users);
  const userValues = Object.values(propValue.users);
  const allKeysAreNumeric = userKeys.every(key => !Number.isNaN(Number(key)));
  userValues.forEach(user => {
    if (typeof user.name !== 'string') {
      isNotValid = ['name', 'string', user.name];
    } else if (typeof user.address !== 'string') {
      isNotValid = ['address', 'string', user.address];
    } else if (typeof user.age !== 'number') {
      isNotValid = ['age', 'number', user.age];
    }
  });

  if (!allKeysAreNumeric) {
    return new Error(
      `Invalid prop '${key}' supplied to ${componentName} component. The keys for the '${key}' object should have the type 'number'.`
    );
  }
  if (isNotValid) {
    return new Error(
      `Invalid prop in '${key}' object supplied to ${componentName} component. The type of '${
        isNotValid[0]
      }' attribute provided was '${typeof isNotValid[2]}' and a '${
        isNotValid[1]
      }' was expected.`
    );
  }
};

Child.propTypes = {
  users: usersObjectPropType
};

這是一個工作演示,您可以在其中將 App 發送的道具類型更改為子組件,並在控制台上查看 PropType 錯誤:

https://stackblitz.com/edit/react-4sunky?file=src/App.js

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM