2017-06-16 68 views
-1

這有什麼錯我的反應下面的setState使用prevState失敗

toggleReply =() => { 
     this.setState(prevState => ({ reply: !prevState.reply })) 
    } 

我知道我可以做this.setState({reply: !this.state.reply}),但上面的代碼也將工作方法,但它並沒有任何線索?

+0

什麼沒有用?有錯誤嗎? – Li357

+1

@AndrewLi有錯誤。 –

+2

它是什麼* ...? – Li357

回答

0

您的setState按照docs的方式工作 - 請嘗試下面的代碼段。這是假設你正確定義了Component類,並且在構造過程中toggleReply處理程序綁定到this,或者您正在使用箭頭函數來調用它。

class Thing extends React.Component { 
 
    constructor(props) { 
 
     super(props); 
 
     this.state = { reply: false }; 
 
     this.toggleReply = this.toggleReply.bind(this); 
 
    } 
 

 
    toggleReply() { 
 
     this.setState(prevState => ({ reply: !prevState.reply })) 
 
    } 
 

 
    render() { 
 
     return (
 
      <div> 
 
       <button onClick={this.toggleReply}>Toggle Reply</button> 
 
       <span>{` ${this.state.reply}`}</span> 
 
      </div> 
 
     ); 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <Thing />, 
 
    document.getElementById('root') 
 
);
<script src=" https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script> 
 
<div id="root"></div>

0

你需要確保ES7類的屬性已啓用:

https://babeljs.io/docs/plugins/transform-class-properties/

那是什麼讓你使用內部進行適當的這個類的箭頭功能綁定。否則,您必須使用其他答案所描述的常規功能手動綁定它。

+0

你不需要ES7 - ES6 arrow功能也將完成這項工作,例如''也可以在我上面的例子中工作,你可以從構造函數中刪除綁定。 – Michael

+0

確定你沒有技術上的需要,但是我從發佈的代碼中假定他/他正在使用ES7類屬性功能。 render()中的手動綁定/箭頭比較慢,我只是使用具有正確Babel配置的類屬性,或者像在答案中那樣在構造函數中綁定它。 – cheesenthusiast