![](/img/trans.png)
[英]Problems with React.js conditional statement within another conditional statement
[英]Where to put conditional statement when setting state in React.js?
我正在使用 React.js 从freeCodeCamp制作番茄钟项目。 我想根据当前的 state 有条件地更改 state。 我是否需要在setState
中使用updater
function 中的this.state
或state
参数?
这是我的代码:
使用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.state
和this.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.