开发者问题收集

ReactJS“TypeError:无法读取未定义的属性‘数组’”

2017-10-13
18895

运行此代码时,我在 App.propTypes 的第一行出现错误

TypeError: Cannot read property 'array' of undefined

代码:

  class App extends React.Component {
   render() {
      return (
         <div>
            <h3>Array: {this.props.propArray}</h3>
            <h3>Array: {this.props.propBool ? "true" : "false"}</h3>
            <h3>Func: {this.props.propFunc(3)}</h3>
            <h3>Number: {this.props.propNumber}</h3>
            <h3>String: {this.props.propString}</h3>
            <h3>Object: {this.props.propObject.objectName1}</h3>
            <h3>Object: {this.props.propObject.objectName2}</h3>
            <h3>Object: {this.props.propObject.objectName3}</h3>
         </div>
      );
   }
}


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
}

App.defaultProps = {
   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"
   }
}

我尝试搜索,但没有得到正确的解决方案。

3个回答

prop-types现在是一个单独维护的库,名为 prop-types 这是React-Docs的解释: 使用proptypes.html

您必须将它们作为

536503538

npm软件包

Agney
2017-10-13

将此:

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
}

更改为:

App.propTypes = {
  propArray: PropTypes.array.isRequired,
  propBool: PropTypes.bool.isRequired,
  propFunc: PropTypes.func,
  propNumber: PropTypes.number,
  propString: PropTypes.string,
  propObject: PropTypes.object
}`
Nitin Singh
2019-03-05

React 软件包不再包含 PropTypes。您需要安装 prop-types 软件包和

import PropTypes from 'prop-types';

编辑:如 文档 第一段所述

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

palsrealm
2017-10-13