【问题标题】:more elegant way to set state [closed]设置状态的更优雅的方式[关闭]
【发布时间】:2018-04-21 19:12:09
【问题描述】:

在以下函数中是否有更优雅或最佳实践的方法来设置状态?

startStop(){

   if(this.state.start === 'Start') startStop = 'Stop'
   else  startStop = 'Start'

   this.setState({start:startStop})

}

【问题讨论】:

  • 我认为放置大括号和分号可能是一大步。 Great topic

标签: react-native setstate


【解决方案1】:

对于标志,而不是字符串 Start/Stop 使用 true-false,

例如:-

    constructor(props){
    this.state={
      start:false
      }
     }

    startStop(){
      this.setState({start:!this.state.start})
      }

render(){
  return<Text>{this.state.start?'Running':'Stopped'}</Text>
}

【讨论】:

    【解决方案2】:

    如果你有类似的东西:

    state = {
      keepGoing: false,
    }
    

    然后您可以执行以下操作来切换:

    this.setState({ keepGoing: !this.state.keepGoing });
    

    【讨论】:

      【解决方案3】:

      this.setState({start:this.state.start==='Start' ? 'Stop' : 'Start'})

      【讨论】:

      • 不,这不起作用,因为它不会来回切换,但如果我们添加 === 'Start' 我们就有了赢家
      • 当然,忘记开始不是布尔值。我的坏
      猜你喜欢
      • 2017-11-12
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 2012-01-29
      • 2021-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多