无法更改状态界面反应+打字稿

无法更改状态界面反应+打字稿

问题描述:

在娄代码,即时得到一个编译错误,我不能在closeLeftCol更改状态: Cannot assign to leftWidth because it is a constant or read only property无法更改状态界面反应+打字稿

interface ILayoutState{ 
     rightClassName: string, 
     leftClassName: string, 
     leftWidth: string, 
     rightWidth : string 
    } 

    export default class Layout extends React.Component<undefined, ILayoutState> { 

     constructor(props) { 
      super(props); 
      this.state = { 
       rightClassName: "right-col slide-in", leftClassName: "left-col slide-in", leftWidth: '' ,rightWidth : '' }; 

     } 

     closeLeftCol() { 
      this.state.leftWidth = "0"; 
      this.state.rightWidth = "100%"; 
      this.state.leftClassName += " hideme"; 
      this.state.rightClassName += " full"; 
      this.forceUpdate(); 
     } 

     render() {...} 

} 

为什么我能够改变它在构造?是什么让它只读? enter image description here

+0

@AndrewLi是不是暗示?为什么我需要打印类型?它在继承时已经是decaler .. – Shazam

Never mutate this.state directly,始终使用setState更新state值。

写这样的:

closeLeftCol() { 
    this.setState(prevState => ({ 
      leftWidth : "0", 
      rightWidth : "100%", 
      leftClassName : prevState.leftClassName + " hideme", 
      rightClassName : prevState.rightClassName + " full" 
    }));    
} 
+0

我们可以在setState中使用'='吗?它不应该是一个有效的js对象吗? – nrgwsth

+0

哦对不起,我的错误(复制粘贴错误),我们不能使用'=',因为它是我们需要使用':'的对象。检查更新的答案:) –

+0

但是,然后我松散打字稿类型提示。它在setstate内不是“强” – Shazam

其它地方则constructor,你需要调用setState方法来改变state

closeLeftCol() { 
      this.setState({ 
       //change state here 
       leftWidth: "0", 
       rightWidth: "100%", 
       leftClassName: this.state.leftClassName + " hideme", 
       rightClassName: this.state.rightClassName + " full" 
      }) 
      //or use this way 
      this.setState((prevState)=>{ 
       return { 
        //change state here 
        leftWidth: "0", 
        rightWidth: "100%", 
        leftClassName: prevState.leftClassName + " hideme", 
        rightClassName: prevState.rightClassName + " full" 
       } 
      }) 
     } 
+0

但是我松散打字稿类型提示。它在setstate内不“强” – Shazam

+0

@Shazam只能使用'setState'更新状态。没有其他方法。但是,您可以通过两种方式使用'setState' - 传递新的状态对象,或者传递一个返回新状态的函数。我已经更新了答案。检查它是否适合你。对不起,我不太了解打字稿类型提示。 – nrgwsth