簡體   English   中英

在 React.js 中設置 state 時在哪里放置條件語句?

[英]Where to put conditional statement when setting state in React.js?

我正在使用 React.js 從freeCodeCamp制作番茄鍾項目。 我想根據當前的 state 有條件地更改 state。 我是否需要在setState中使用updater function 中的this.statestate參數?

這是我的代碼:

使用state參數:

this.setState(state => {
    let newState = {}
    if (state.timer === 0){
        this.beep.current.play()
        if (state.type === 'Session') {
            newState.timer = state.break * 60
            newState.type = 'Break'
        } else {
            newState.timer = state.session * 60
            newState.type = 'Session'
        }
    } else {
        newState.timer = state.timer - 1
    }
    return newState
})

使用this.state

if (this.state.timer === 0) {
    this.beep.current.play()
    if (this.state.type === 'Session') {
        this.setState(state => ({
            timer: state.break * 60,
            type: 'Break'
        }))
    } else {
        this.setState(state => ({
            timer: state.session * 60,
            type: 'Session'
        }))
    }
} else {
    this.setState(state => ({
        timer: state.timer - 1
    }))
}

如果您需要更多上下文,可以使用this.statethis.state使用 this.state 在 CodePen 上查看這兩個代碼。 您可以在左上角運行測試。 正如您在 CodePen 中看到的,兩個代碼都通過了測試。 我應該使用哪一個,為什么?

Anytime you want to make changes to the state that depend on the previous state you should pass a function that receives the previous state as a parameter. If you use this.state instead, you might get some unexpected behaviour because the setState method is asynchronous, so you can't actually guarantee that the values stored in this.state will be the ones from the previous state when the state is actually updated

tldr; 使用您提到的第一個選項

暫無
暫無

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

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