调用React类的构造函数时的不变量冲突

Invariant Violation when calling constructor on React class

本文关键字:不变量 冲突 构造函数 调用 React      更新时间:2023-09-26

我正在开始使用React,我正在尝试定义一个具有构造函数类的新组件。我的更复杂的元素不起作用,所以我尝试了从文档中看到的示例。这是我的JS文件

let React = require('react');
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
  }
  tick() {
    this.setState({count: this.state.count + 1});
  }
  render() {
    return (
      <div onClick={this.tick.bind(this)}>
        Clicks: {this.state.count}
      </div>
    );
  }
}
Counter.propTypes = { initialCount: React.PropTypes.number };
Counter.defaultProps = { initialCount: 0 };
React.render(
  <Counter />,
  document.getElementById('content')
);

直接取自React的文档。然而,当我加载页面时,我在控制台中得到错误Uncaught Error: Invariant Violation: ReactClassInterface: You are attempting to define 'constructor' on your component more than once. This conflict may be due to a mixin.

现在我在我的整个应用程序中使用Material UI和React-Router,并且加载在我的Vendor文件中,但我在这个文件中根本没有需要它们。有什么想法吗?

不要使用构造函数,而是使用本地的getInitialeState函数。你不需要超级函数,我不确定在这里使用ES6是否有用和清晰。

也总是使用setState和never state =//这是一个非常糟糕的做法从文档中"永远不要改变这个。直接调用setState(),因为之后调用setState()可能会替换您所做的更改。对待这个问题。状态就好像它是不可改变的。"

https://facebook.github.io/react/docs/component-api.html

我读过一篇博客文章,建议你做一些事情,比如state=//stuffhttp://www.newmediacampaigns.com/blog/refactoring-react-components-to-es6-classes也许你已经受到了启发,但就我自己而言,我不会听从一个家伙的建议去做与文档中建议相反的事情。(从未改变…)。

非常感谢Kyle和Gabdallah的测试和确认它的工作。原来是Material UI弄乱了代码(巧合的是,我真的不推荐这样做——对我的口味来说太死板了)。

重申一下,这个例子直接取自React文档,是使用ES6的推荐方式。希望这对将来的人有所帮助!