Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何使用React TypeScript 2.0更改状态?_Reactjs_Typescript_Typescript2.0 - Fatal编程技术网

Reactjs 如何使用React TypeScript 2.0更改状态?

Reactjs 如何使用React TypeScript 2.0更改状态?,reactjs,typescript,typescript2.0,Reactjs,Typescript,Typescript2.0,对于由React和TypeScript创建的如此小的组件 interface Props { } interface State { isOpen: boolean; } class App extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { isOpen: false }; } p

对于由React和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);
  }

}
我想可能是这个变化造成的

所以我只想打开国旗

我该怎么办?有人知道解决方法吗

谢谢

更新 快速解决方法如下所示

this.setState({ isOpen: true });

即使没有typescript,您的操作方式也是一个问题。 这一行特别是一个问题

this.state.isOpen = true;
这一行代码试图直接改变状态,这不是做事情的反应方式,也正是typescript试图执行的

改变状态的一种方法是复制一个状态,在你的情况下,它看起来像这样

let state = Object.assign({}, this.state)
state.isOpen = true;
现在您有了状态的副本,并且当更改局部变量时,您并没有更改状态

错误发生在

  private someHandler() {
    // I just want to turn on the flag. but compiler error occurs.
    this.state.isOpen = true;
    this.setState(this.state);
  }
因为
状态
是不可变的。幸运的是,您使用的是TypeScript,它在编译时为您捕捉到了这一点

正确代码 可以合并对象:

  private someHandler() {
    this.setState({...this.state, isOpen: true});
  }

更多信息:

在使用基于类的组件时,使用
setState()
方法设置状态会将isOpen属性合并到现有状态。因此,这将起作用:

this.setState({isOpen: true});

这是一个教科书上的例子,说明了使用某种形式的打字系统(如Typescript或React)的好处。它捕获类似的内容,并帮助您编写正确、惯用的React代码。只读是通过Object.assign()来维护的。这是正确的语法吗?this.setState({…this.state,{isOpen:true}});或者this.setState({…this.state,isOpen:true})@三川固定
this.setState({isOpen: true});