For such a small component created by React and TypeScript.
interface Props {
}
interface State {
isOpen: boolean;
}
class App extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
isOpen: false
};
}
private someHandler() {
// I just want to turn on the flag. but compiler error occurs.
this.state.isOpen = true;
this.setState(this.state);
}
}
When I tried to upgrade TypeScript 1.8 to 2.0, then I got the compiler error like below.
error TS2540: Cannot assign to 'isOpen' because it is a constant or a read-only property.
I guess maybe it caused by this change.
so I just want to turn on the flag.
What should I do? Does anyone know the workaround?
Thanks.
the quick workaround is just doing like the below.
this.setState({ isOpen: true });
The way that you are doing it would be a problem even without typescript. This line specifically is a issue.
this.state.isOpen = true;
This line of code is attempting to mutate state directly which is not the react way of doing things and precisely what typescript is trying to enforce.
One way to work with changing state, is by making a copy of the state which in your case would look like this;
let state = Object.assign({}, this.state)
state.isOpen = true;
Now you have a copy of state and when changing your local variable you are not changing state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With