ReactJS “TypeError: Cannot read property 'array' of undefined”

前端 未结 4 706
感情败类
感情败类 2021-01-04 05:31

While running this code I got error on the first line on App.propTypes

TypeError: Cannot read property \'array\' of undefined

相关标签:
4条回答
  • 2021-01-04 06:08

    Prop-Types are now a separately maintained library named prop-types Here is the explanation from react-docs: https://reactjs.org/docs/typechecking-with-proptypes.html

    You have to import them as

    import React from 'react';
    import PropTypes from 'prop-types'
    
    class App extends React.Component {
      //App here
    }
    
    App.propTypes = {
     propArray: PropTypes.array.isRequired, 
     propBool: PropTypes.bool.isRequired,
     propFunc: PropTypes.func,
     propNumber: PropTypes.number,
     propString: PropTypes.string,
     propObject: PropTypes.object
    }
    

    NPM Package

    0 讨论(0)
  • 2021-01-04 06:15

    You should change React.PropTypes.array.* to PropTypes.array.*

    App.propTypes = {
       propArray: PropTypes.array.isRequired,
       propBool: PropTypes.bool.isRequired,
       propFunc: PropTypes.func,
       propNumber: PropTypes.number,
       propString: PropTypes.string,
       propObject: PropTypes.object,
    	 headerProp: PropTypes.string,
    	 contentProp: PropTypes.string
    }
    App.defaultProps = {
    		headerProp: "Header from props...",
    		contentProp:"Content from props...",
    		propArray: [1,2,3,4,5],
    		propBool: true,
    		propFunc: function(e){return e},
    		propNumber: 1,
    		propString: "String value...",
    
    		propObject: {
    			objectName1:"objectValue1",
    			objectName2: "objectValue2",
    			objectName3: "objectValue3"
    		}
    }

    0 讨论(0)
  • 2021-01-04 06:21

    Change this:

    App.propTypes = {
       propArray: React.PropTypes.array.isRequired, //I got error over here
       propBool: React.PropTypes.bool.isRequired,
       propFunc: React.PropTypes.func,
       propNumber: React.PropTypes.number,
       propString: React.PropTypes.string,
       propObject: React.PropTypes.object
    }
    

    to:

    App.propTypes = {
      propArray: PropTypes.array.isRequired,
      propBool: PropTypes.bool.isRequired,
      propFunc: PropTypes.func,
      propNumber: PropTypes.number,
      propString: PropTypes.string,
      propObject: PropTypes.object
    }`
    
    0 讨论(0)
  • 2021-01-04 06:24

    The React package no longer contains PropTypes. You need to install the prop-types package and

    import PropTypes from 'prop-types';
    

    Edit: As stated in the first paragraph in the documentation

    React.PropTypes has moved into a different package since React v15.5. Please use the prop-types library instead.

    0 讨论(0)
提交回复
热议问题