reactjs – 如何使用React TypeScript 2.0更改状态?
发布时间:2020-12-15 16:19:53 所属栏目:百科 来源:网络整理
导读:对于由React和TypeScript创建的这样一个小组件. interface Props {}interface State { isOpen: boolean;}class App extends React.ComponentProps,State { constructor(props: Props) { super(props); this.state = { isOpen: false }; } private someHandle
对于由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); } } 当我尝试将TypeScript 1.8升级到2.0时,我得到了如下编译器错误. error TS2540: Cannot assign to 'isOpen' because it is a constant or a read-only property. 我想也许是因为这种变化造成的. > https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-getters-without-setters-not-considered-read-only 所以我只想打开旗帜. 我该怎么办?有谁知道解决方法? 谢谢. 更新 快速解决方法就像下面这样做. this.setState({ isOpen: true }); 解决方法
即使没有打字稿,你这样做的方式也会成为一个问题.
这条线特别是一个问题. this.state.isOpen = true; 这行代码试图直接改变状态,这不是做事的反应方式,而是确切地试图强制执行的打字稿. 处理改变状态的一种方法是制作一个状态的副本,在你的情况下看起来像这样; let state = Object.assign({},this.state) state.isOpen = true; 现在你有一个状态副本,当你改变你的局部变量时,你没有改变状态. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |