Reactjs 无法访问状态

Reactjs 无法访问状态,reactjs,typescript,Reactjs,Typescript,正在尝试访问我的方法内部的状态,但它始终为空。有谁能解释一下我需要做些什么来给我的方法引用state,以及为什么需要这样做 import * as React from 'react'; interface IProps { enabled?:boolean; } interface IState { itemCount?: number; } class ItemCounter extends React.Component<IProps, IState> { p

正在尝试访问我的方法内部的状态,但它始终为空。有谁能解释一下我需要做些什么来给我的方法引用state,以及为什么需要这样做

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;
import*as React from'React';
接口IProps{
启用?:布尔值;
}
界面状态{
itemCount?:编号;
}
类ItemCounter扩展了React.Component{
公共国家:IState
建造师(道具:IProps){
超级(道具)
此.state={
项目计数:0
};
}
公共处理增量=()=>{
if(this.state.itemCount!=null){
this.setState({itemCount:this.state.itemCount++});
}
};
公开披露=()=>{
if(this.state.itemCount!=null){
this.setState({itemCount:this.state.itemCount--});
}
};
公共渲染(){
返回(
{this.state.itemCount}
添加项
删除项目
);
}
}
导出默认项计数器;

您没有定义多个handleIncrement和HandleDeprement

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});
  }
};

在React
state
属性上使用
++
--
是不允许的。这两个操作符都会改变它们所使用的数据,这是您永远不希望在React
state

上使用的?你在用包裹吗?这很有效。我把它公之于众是因为create-react应用程序的linter不会编译代码,除非这些方法是用prviate、public或protected修饰的。如果你对此感兴趣,我会禁用它,因为这是一个糟糕的建议哇,我觉得很傻。谢谢你花时间来帮助我,我很感激。很高兴帮助:)附带说明
this.state.itemCount++
将首先返回
this.state.itemCount
的值,然后将该值增加1
++this.state.itemCount
会将该值增加1,然后返回新增加的值。但同样,在React
状态下无法执行的操作