无法访问状态

时间:2018-04-26 00:44:41

标签: reactjs typescript

尝试访问我方法中的状态,但这始终为null。任何人都可以向我解释我需要做些什么才能让我的方法参考状态以及为什么需要这样做?

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;

2 个答案:

答案 0 :(得分:1)

你错过了定义一些handleIncrement和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});
  }
};

Edit 6j42kr2j4w

答案 1 :(得分:0)

在React ++属性上使用--state是禁忌。这两个运算符都会改变它们所使用的数据,这是你在React state

上所不想要的。