我想在内部使用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>
);
}
}
也许您喜欢使用
if (mainuser === 'User1'){
this.setState(prevState => {applauded: prevState.applauded + 1})
} else if (mainuser === 'User2') {
this.setState(prevState => {applauded1: prevState.applauded1 + 1})
}
尝试以这种方式:
const countapplauded= (mainuser==="User1"? this.state.applauded+ 1: this.state.applauded + 2);