關於 React 小書:可把函式當作參數傳入 setState


Posted by YongChenSu on 2020-12-09

無法這樣使用 setState

handleClickOnLikeButton () {
  this.setState({ count: 0 }) // => this.state.count 还是 undefined
  this.setState({ count: this.state.count + 1}) // => undefined + 1 = NaN
  this.setState({ count: this.state.count + 2}) // => NaN + 2 = NaN
}


可把函式當作參數傳入 setState

handleClickOnLikeButton () {
  this.setState((prevState) => {
    return { count: 0 }
  })
  this.setState((prevState) => {
    return { count: prevState.count + 1 } // 上一个 setState 的返回是 count 为 0,当前返回 1
  })
  this.setState((prevState) => {
    return { count: prevState.count + 2 } // 上一个 setState 的返回是 count 为 1,当前返回 3
  })
  // 最后的结果是 this.state.count 为 3
}

總結

多次使用 setState 只會重新渲染一次,不用擔心多次使用 setState 帶來效能較差的問題。

參考資源


#程式導師實驗計畫第四期 #前端 #React #react 小書 #setstate







Related Posts

Unlocking Digital Success: The Pinnacle of SEO Services in Dubai

Unlocking Digital Success: The Pinnacle of SEO Services in Dubai

資料庫架構及運動比賽定義

資料庫架構及運動比賽定義

每日心得筆記 2020-06-26(五)

每日心得筆記 2020-06-26(五)


Comments