簡體   English   中英

為什么 output 與 React setState() 不同

[英]Why is the output different with React setState()

我不知道為什么

  • 當我使用this.setState({count: count+1}點擊多次只會更新一次計數
  • 當我使用this.setState({count: this.setState.count})時,每次點擊都會更新計數
  • 為什么不同?
       class Demo extends React.Component {
            state = {count: 0};
            render() {
                const {count} = this.state;
                return  <button onClick={() => this.setState({count: count+1})}>count</button>
            }
            shouldComponentUpdate(){
                return false;
            } 

        }
  • 環境react@16.8.4

因為他們的范圍不同。

this.setState({count: this.setState.count+1})加載state.count號和重新分配的操作在同一個 onClick 事件 scope 中。

但是this.setState({count: count+1})中的count變量定義在 upper render() scope 和 onClick 事件中只接收count作為上層變量。 因此,render() function只運行一次,所以count in render()只初始化一次(loading state.count only once); 當你點擊按鈕時,只會執行 onClick 事件 scope(重新分配動作會執行多次),而不是render() scope。這就是為什么 onClick 事件中的count變量將始終為 0。

您的案例有一個簡單的等效示例:

 state={count:0} function upperLevel() { let {count} = state; function downlevel() { state = { count: count + 1 } console.log(state); } downlevel(); downlevel(); downlevel(); } upperLevel()

如果我們移動let {count} = state; 進入downlevel()則數字將增加。

 state = {count: 0} function upperLevel() { //let {count} = state; function downlevel() { let {count} = state; state = {count: count + 1 } console.log(state); } downlevel(); downlevel(); downlevel(); } upperLevel()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM