2017-08-07 63 views
2

對於由React和TypeScript創建的這樣一個小組件。如何使用React TypeScript 2.0更改狀態?

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. 

我想也許是由這個變化引起的。

,所以我只是想打開標誌。

我該怎麼辦?有誰知道解決方法?

謝謝。

更新

快速解決方法就像下面這樣做。

this.setState({ isOpen: true }); 

回答

4

即使沒有打字稿,你這樣做的方式也是一個問題。 這條線特別是一個問題。

this.state.isOpen = true; 

這行代碼試圖直接變異狀態,這是不是反應處事及正是打字稿試圖強制執行的方式。

一種改變狀態的方法是通過製作一份你的情況的副本,看起來像這樣;

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); 
    } 

+0

這是使用某種形式的像打字稿或輸入做出反應體系的好處典型例子。它捕獲這樣的事情,並幫助您編寫正確的,慣用的React代碼。 – GregL

2

錯誤,因爲state不可變。幸運的是,您正在使用TypeScript,它在編譯時爲您着想。

正確的代碼

您可以合併的對象:

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

更多:https://basarat.gitbooks.io/typescript/content/docs/spread-operator.html

+0

這是正確的語法嗎? this.setState({... this.state,... {isOpen:true}}); 或 this.setState({... this.state,isOpen:true}); – mitsuruog

+0

@MitsuruOgawa修復 – basarat

相關問題