You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js:如何结合自定义函数与Shape校验PropTypes数组结构及长度

Combine Array Length and Structure Validation in Custom PropTypes

Got it, let's merge both the array structure check and length validation into one custom PropTypes function. The key here is to reuse the existing shape validation logic you already have, so you don't have to rewrite all those property checks manually.

Step-by-Step Solution

First, define your original structure validator as a reusable variable—this lets us call it inside our custom function:

// Reuse your existing shape validation logic
const dataSourceStructure = PropTypes.arrayOf(
  PropTypes.shape({
    share: PropTypes.number,
    visibleInLegend: PropTypes.bool,
    order: PropTypes.number,
    color: PropTypes.string
  })
);

Then, create your unified custom validator function that runs both checks in sequence:

dataSource: function(props, propName, componentName) {
  const dataSource = props[propName];

  // 1. First check: Ensure the value is actually an array (prevents runtime errors)
  if (!Array.isArray(dataSource)) {
    return new Error(
      `Invalid prop \`${propName}\` supplied to \`${componentName}\`, expected an array. Validation failed.`
    );
  }

  // 2. Second check: Run the original structure validation
  const structureValidationError = dataSourceStructure(props, propName, componentName);
  if (structureValidationError) {
    return structureValidationError;
  }

  // 3. Third check: Verify array length is exactly 2
  if (dataSource.length !== 2) {
    return new Error(
      `Invalid array length \`${dataSource.length}\` (expected 2) for prop \`${propName}\` supplied to \`${componentName}\`. Validation failed.`
    );
  }

  // If all checks pass, return nothing (undefined = validation success)
}

How It Works

  • Array Type Guard: We first confirm the prop is an array to avoid errors when accessing .length or running the structure validator.
  • Reuse Existing Structure Checks: Instead of rewriting all the shape validations, we call your pre-defined structure validator and pass through any error it generates.
  • Length Validation: Finally, we check if the array length matches your requirement of exactly 2, returning a targeted error if it doesn't.

This unified function will catch both invalid array structures and incorrect lengths, returning clear, specific errors for each case.

内容的提问来源于stack exchange,提问作者Zied Hf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:50:53