New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Having this.state in the constructor and this.setState everywhere else is violating the "Uniform access principle" #7212
Comments
We definitely won’t be using ES proxies in production builds because they are a new feature and not supported in older browsers. I generally agree this is confusing. The justification I heard from @sebmarkbage is that while constructor runs, the instance doesn’t exist in I don’t, however, quite see why we couldn’t make I think another intention was that you’d never write constructor logic at all, and instead you would use property initializer syntax ( |
Do you feel that
Maybe if you were allowed to update state with |
Technically, the best way to "setState" is initializer @gaearon That'd be the only case where You can also store it in a side-table. You also need to store the second argument to The side-table thing violates the composition pattern: class Foo extends Component {
constructor(props, context) {
this._wrapped = new OtherComponent(props, context, customUpdater);
}
...
} class Bar extends OtherComponent {
constructor() {
return {
__proto__: new.target.prototype,
_wrappedAllocation: super()
};
}
} Who know what other weird class semantics are not possible if you break the rules. Classes are just weird. |
Could be a stupid suggestion, but this could possibly be mitigated by:
This would allow the use of |
I think they are different operations. In Using the terminology of this potential TS feature: microsoft/TypeScript#4889 - in those terms, if a component's state is of type |
We likely won't do this. If property initializers get into the language, you'd just As for We will likely revisit all lifecycles after shipping Fiber (#7678) and we'll keep this in mind when designing the new ones. |
ES6 style of creating components in React is clearly violating the Uniform access principle. It's a general source of confusion (and bugs) to be able to set state in two different ways:
this.state = {}
if you're in the constructorthis.setState()
everywhere else.I believe it'd be much better to have just 1 way to set state in general, and it should be universal. If we're already accessing state through
this.state
, and setting state in the constructor withthis.state
, why not do it everywhere else? The behavior ofthis.setState
could be easily replicated with ES6 Proxies.The text was updated successfully, but these errors were encountered: