Reactjs 如何使用React TypeScript 2.0更改状态?
对于由React和TypeScript创建的如此小的组件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
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});