2017-10-13 76 views
0

在运行这段代码我在App.propTypesReactJS“类型错误:无法读取属性的‘数组’未定义”

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

我试图寻找,但我没有得到正确的解决方案。

+0

您正在使用哪个版本的React? –

+1

我猜你在React 16上,PropTypes已经移动到另一个名为prop-types的包。 - https://reactjs.org/warnings/dont-call-proptypes.html –

+0

@BoyWithSilverWings反应版本:16.0.0 –

回答

7

道具类型中第一款规定,现在命名为单独维护库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 Package

+1

这解决了我的问题!谢谢 –

+0

我也'从'prop-types'中导入PropTypes;'但它没有工作 – Bhargav

+0

你还有同样的错误吗? –

0

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

import PropTypes from 'prop-types'; 

编辑:正如documentation

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

相关问题