当前位置: 首页 > 知识库问答 >
问题:

ReactJS“TypeError:无法读取未定义的属性”array“

沈永新
2023-03-14

运行此代码时,在app.proptypes的第一行出现错误

TypeError:无法读取未定义的属性“array”

代码:

  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"
   }
}

我试着搜索,但没有得到正确的解。

共有2个答案

裴存
2023-03-14

更改此:

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
}`
湛玄裳
2023-03-14

Prop-Types现在是一个单独维护的库,名为Prop-Types这里是react-docs的解释:https://reactjs.org/docs/typechecking-with-proptypes.html

您必须将它们导入为

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包

 类似资料: