gpt4 book ai didi

javascript - 在 React 类上调用构造函数时发生不变冲突

转载 作者:行者123 更新时间:2023-12-02 15:53:16 24 4
gpt4 key购买 nike

我正在开始使用 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试图在组件上多次定义“构造函数”。此冲突可能是由于控制台中的 mixin 造成的。

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

最佳答案

不要使用构造函数,而应使用 native getInitialeState 函数。你不需要 super 函数,我不确定在这里使用 ES6 是否有用和清晰。

始终使用 setState 而从不使用 state =//soemthing/这是一个非常糟糕的做法从文档中“永远不要直接改变 this.state,因为之后调用 setState() 可能会替换您所做的改变。将 this.state 视为不可变的。”

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

我读过这篇博客文章,建议您做诸如 state=//stuf 之类的事情 http://www.newmediacampaigns.com/blog/refactoring-react-components-to-es6-classes也许你受到了它的启发,但是,就我自己而言,我不会遵循一个人写的建议去做与文档中建议相反的事情。 (永远不要变异...)。

希望对您有所帮助。

关于javascript - 在 React 类上调用构造函数时发生不变冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31727266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com