Я пишу простой калькулятор в React. Я пытаюсь обновить состояние компонента в зависимости от того, какая кнопка нажата (как и следовало ожидать). Состояние компонента выглядит следующим образом:
this.state = {
total: null,
next: null,
operation: null,
}
В настоящее время у меня есть одна длинная инструкция if / else, которая проверяет кучу сценариев ios, чтобы определить, какими должны быть соответствующие значения. Мне интересно, как я мог бы переписать это, чтобы уменьшить сложность функции:
handleClick(buttonName) {
let { total, next } = this.state;
const { operation } = this.state;
let obj;
const nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
const syms = ['+', '-', 'X', '/', '%'];
const equal = '=';
const reset = 'AC';
const decimalPoint = '.';
if (total === null && nums.indexOf(buttonName) >= 0) {
this.setState({
total: buttonName,
});
} else if (total !== null
&& buttonName === decimalPoint
&& (total.indexOf(decimalPoint) === -1)) {
this.setState({
total: total += buttonName,
});
} else if (total !== null
&& next !== null
&& buttonName === decimalPoint
&& (next.indexOf(decimalPoint) === -1)) {
this.setState({
next: next += buttonName,
});
} else if (total !== null
&& operation === null
&& syms.indexOf(buttonName) >= 0) {
this.setState({
operation: buttonName,
});
} else if (total !== null
&& operation === null
&& nums.indexOf(buttonName) >= 0) {
this.setState({
total: total += buttonName,
});
} else if (total !== null
&& operation !== null
&& next === null
&& nums.indexOf(buttonName) >= 0) {
this.setState({
next: buttonName,
});
} else if (total !== null
&& operation !== null
&& next !== null
&& nums.indexOf(buttonName) >= 0) {
this.setState({
next: next += buttonName,
});
} else if (total !== null
&& operation !== null
&& next !== null
&& ((buttonName === equal) || (buttonName === reset))) {
obj = method.calculate(this.state, operation);
this.setState({
total: obj.total,
next: obj.next,
operation: buttonName,
});
}
}
PS. функция method.calculate указана в другом модуле.