React Proptype for array及其属性

时间:2018-04-05 20:22:14

标签: reactjs react-proptypes

我有一个“this.props.invoiceList”数组,我根据这个数组做了一些功能“filter,map and length”

我收到了以下lint错误:

error  'invoiceList' is missing in props validation         react/prop-types
error  'invoiceList.filter' is missing in props validation  react/prop-types
error  'invoiceList.map' is missing in props validation     react/prop-types
error  'invoiceList.length' is missing in props validation  react/prop-types

我需要帮助来修复它,我尝试了以下方法,但我没有得到正确的解决方案

  1. invoiceList:PropTypes.array,
  2. invoiceList:PropTypes.arrayOf(PropTypes.length)
  3. withShape(PropTypes.array,{length:PropTypes.number})

1 个答案:

答案 0 :(得分:1)

您需要为组件中的每个道具设置验证。

您可以按照以下方式执行此操作:

import {PropTypes} from 'prop-types';
...
*YourComponentName*.propTypes = {
    invoiceList: PropTypes.array.isRequired
} 

如果它是一个对象数组,并且您想进一步验证,则可以执行以下操作:

    invoiceList: PropTypes.arrayOf(
       PropTypes.shape({
           name: PropTypes.string.isRequired,
           description: PropTypes.string.isRequired
       })
   ).isRequired

这应解决掉毛错误。

您可以在此处详细了解PropTypes;

https://reactjs.org/docs/typechecking-with-proptypes.html

相关问题