2017-05-31 47 views
0

在婁代碼,即時得到一個編譯錯誤,我不能在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

回答

1

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

0

其它地方則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