Reputation: 111
Trying to access state inside of my methods but this is always null. Can anyone explain to me what I need to do to give my methods reference to state and why it needs to be done?
import * as React from 'react';
interface IProps {
enabled?:boolean;
}
interface IState {
itemCount?: number;
}
class ItemCounter extends React.Component<IProps, IState> {
public state : IState
constructor(props: IProps) {
super(props)
this.state = {
itemCount: 0
};
}
public handleIncrement = () => {
if(this.state.itemCount != null){
this.setState({itemCount: this.state.itemCount++});
}
};
public handleDecrement = () => {
if(this.state.itemCount != null){
this.setState({itemCount: this.state.itemCount--});
}
};
public render() {
return (
<div>
{this.state.itemCount}
<button onClick={this.handleIncrement}>Add Item</button>
<button onClick={this.handleDecrement}>Remove Item</button>
</div>
);
}
}
export default ItemCounter;
Upvotes: 0
Views: 64
Reputation: 341
using ++
or --
on a React state
property is a no-no. both of those operators will mutate the data they are used on, which is something you never want to so on a React state
Upvotes: 0
Reputation: 6743
You missed defining a number of handleIncrement and handleDecrement
public handleIncrement = () => {
if(this.state.itemCount != null){
this.setState({itemCount: this.state.itemCount+1});
}
};
public handleDecrement = () => {
if(this.state.itemCount != null){
this.setState({itemCount: this.state.itemCount-1});
}
};
Upvotes: 1