当前位置: 代码迷 >> JavaScript >> 在React类上调用构造函数时会发生不变违规
  详细解决方案

在React类上调用构造函数时会发生不变违规

热度:73   发布时间:2023-06-05 14:03:02.0

我开始使用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. 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,并且永远不要使用state = // soemthing /,这是一个非常糟糕的做法。从文档“永远不要直接更改this.state,因为之后调用setState()可能会替换您所做的更改。将this.state视为一成不变的。”

我读过这篇博客文章,建议您做state = // stuf 类的事情,也许您对此有所启发但是,就我自己而言,我不会遵循一个人写的建议来做与文档中建议相反的事情。 永不变异... )。

希望对您有所帮助。

非常感谢Kyle和Gabdallah进行了测试并确认它可以正常工作。 事实证明,是材料UI弄乱了代码(巧合的是,我不建议这样做-太严格了,不能满足我的口味)。

重申一下,此示例直接来自React文档,是使用ES6的推荐方法。 希望这对以后的人有所帮助!

  相关解决方案