2017-10-04 146 views
1

我正在遵循React教程here。在第四课中,我创建了一个App.propTypes部分。当我运行代码时,React给我一个错误说TypeError: Cannot read property 'string' of undefined当我打开我的控制台时,错误说React.PropTypes is deprecated since React 15.5.0, use the npm module prop-types instead。然后我继续安装npm包prop-types并将其导入到我的代码中,但我仍然以相同的错误结束。我将在下面包含我的代码。React.PropTypes已弃用,且已安装道具类型包

我正在使用节点版本v8.5.0。也许我应该尝试找出教程使用的节点版本,以便我的React版本匹配,但我甚至不知道我是否可以找到它,我希望教程能够指定这些类型的东西,看起来像这样教程是2岁,这可能是为什么我有这种差异。

的src/app.js

import React from 'react'; 
import PropTypes from 'prop-types'; 

class App extends React.Component{ 
    render(){ 
    let txt = this.props.txt 
    return (
     <div> 
     <h1>{txt}</h1> 
     <b>bold</b> 
     </div> 
    ) 
    } 
} 

App.propTypes = { 
    txt: React.PropTypes.string, 
    cat: React.PropTypes.number.isRequired 
} 

export default App; 

/src/index.js

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import App from './App'; 

ReactDOM.render(
    <App cat={5} txt="this is the prop value" />, 
    document.getElementById('root') 
); 
+2

'txt:React.PropTypes.string' =>'txt:PropTypes.string' –

回答

3

变化

txt: React.PropTypes.string, 
cat: React.PropTypes.number.isRequired 

txt: PropTypes.string, 
cat: PropTypes.number.isRequired 

你必须导入为PropTypes从“丙类” PropTypes所以没有必要使用PropTypes作为进行反应的特性。使用PropType作为React的属性几个月前已弃用。

此外,您将猫标记为isRequired,但不要在App组件的任何位置使用它。所以这将显示一个lint错误。

除此之外,我不确定问题是什么。我在我的机器上运行了你的源代码,它出来了。

1

如果您使用的道具类型包,你可以这样做:

App.propTypes = { 
    txt: PropTypes.string, 
    cat: PropTypes.number.isRequired 
} 

此外,您的ge错误tting是因为你没有猫作为道具进入任何地方。

-3

也许你需要使用这个包here

0

我遵循相同的教程,并通过执行以下操作解决它。

部分1

  • 丙类型安装

    1. sudo npm -i -g prop-types

    2. 在App.js

      • 确保import PropTypes from 'prop-types';位于文件的顶部。
    3. 变化

      App.propTypes = { txt: React.PropTypes.string, cat: React.PropTypes.number.isRequired }

      App.propTypes = { txt: PropTypes.string,//------------ remove React cat: PropTypes.number.isRequired//-- remove React }

部2

  • 重新安装node_modules

    1. 删除套餐的以.json NOT的package.json
    2. 运行sudo npm install
    3. npm start

参考文献https://www.npmjs.com/package/prop-types

Ref。 https://github.com/facebookincubator/create-react-app/issues/2534