【问题标题】:How to use const in if (React Native)如何在 if (React Native) 中使用 const
【发布时间】:2019-02-14 15:03:23
【问题描述】:

我想在 if(条件分支) 中使用 const, 但我无法在 if 中设置 const。

有没有办法在条件分支中使用 const 或设置变量? 还是我的代码有问题?

请给点建议好吗?

export default class ApplauseButton extends Component {

  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      applause: 100,
      applauded: 0,
    };
  }

  handlClick= async ()=> {
      const {
        mainuser,
        subuser,
      } = this.props;

      if (mainuser === 'User1'){
        const countapplauded = this.state.applauded + 1;
      } else if (mainuser === 'User2') {
        const countapplauded1 = this.state.applauded1 + 1;
      }
  };

  render() {
    const {
      mainuser,
      subuser,
    } = this.props;

    return (
      <View style={styles.container}>
        <TouchableHighlight
          onPress={() => {this.handlClick()}}
          onLongPress={this._onLongPressButton} underlayColor="white">
          <View style={styles.button}>
            <Text style={styles.buttonText}>????</Text>
          </View>
        </TouchableHighlight>
      </View>
    );
  }
}

【问题讨论】:

  • const 定义的变量是块范围的,所以它们在if/else 块之后将不存在。你想用countapplaudedcountapplauded1 做什么?您没有将它们用于任何事情。
  • @Tholle 感谢您的评论!我不明白变量只存在于 if/esle 中。现在,我的代码成功了!

标签: reactjs react-native react-redux


【解决方案1】:

也许你喜欢用

if (mainuser === 'User1'){
   this.setState(prevState => {applauded: prevState.applauded + 1})
} else if (mainuser === 'User2') {
   this.setState(prevState => {applauded1: prevState.applauded1 + 1})
}

【讨论】:

    【解决方案2】:

    试试这个方法:

    const countapplauded= (mainuser==="User1"? this.state.applauded+ 1: this.state.applauded + 2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      • 2018-02-05
      • 2019-08-31
      • 2019-10-20
      • 2019-02-17
      • 1970-01-01
      相关资源
      最近更新 更多