2017-10-04 68 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