如何在if(React Native)中使用const

时间:2019-02-14 15:03:24

标签: reactjs react-native react-redux

我想在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>
    );
  }
}

2 个答案:

答案 0 :(得分:1)

也许您想使用

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

答案 1 :(得分:0)

尝试这种方式:

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