React.PropTypes 已弃用,我已经安装了 prop-types 包

React.PropTypes is deprecated and I have installed prop-types package

我正在学习 React 教程 here. In the fourth lesson it has me create a App.propTypes section. When I run the code React gives me a error saying TypeError: Cannot read property 'string' of undefined when I open up my console the error says React.PropTypes is deprecated since React 15.5.0, use the npm module prop-types instead. I then went ahead and installed the npm package prop-types 并将其导入到我的代码中,但我仍然遇到同样的错误。我将在下面包含我的代码。

我正在使用节点版本 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')
);

如果您使用的是 prop-types 包,您可以这样做:

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

另外,你得到的错误是因为你还没有猫作为道具进入任何地方。

改变

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

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

您已将 PropTypes 作为 PropTypes 从 'prop-types' 导入,因此无需将 PropTypes 用作 React 的 属性。使用 PropTypes 作为 React 的 属性 几个月前就被弃用了。

此外,您将 cat 标记为 isRequired,但不要在 App 组件中的任何地方使用它。这样会显示 lint 错误。

除此之外,我不确定是什么问题。我 运行 你的源代码在我的机器上,结果没问题。

也许你需要用到这个包here

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

第 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

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