我有以下减速器:
export const showResult = (state = [], action) => {
switch (action.type) {
case 'GET_NUMBER':
return [
...state,
action.n
]
case 'CLEAR_NUMBER':
return [
...state
].pop()
case 'RESET_RESULT':
return []
default:
return state
}
}
" CLEAR_NUMBER" " deleteNumber"点击:
import React, { Component } from 'react'
import Display from './Container'
import Operator from './Container'
import { selectOperator } from './../util'
class Calculator extends Component {
constructor(props) {
super(props)
this.state = {
val1: '',
val2: ''
}
}
displayNumber = e => {
const { getNumber, resetResult, getOperator } = this.props
getNumber(parseInt(e.target.dataset.n))
}
getOperator = e => {
const { getOperator, n, resetResult, resetOperator } = this.props
resetOperator()
getOperator(e.target.dataset.sign)
if(this.state.val1 == "") {
this.setState({
val1: n
})
resetResult()
}
}
getSum = val => {
val.reduce((acc, val) => acc + val)
}
deleteNumber = () => {
const { clearNumber } = this.props
clearNumber()
}
getTotal = () => {
const { n, operator, resetResult } = this.props,
{ val1, val2 } = this.state,
value1 = this.getSum(val1),
value2 = val2 != "" ? this.getSum(val2) : null;
let operatorVal = operator[0]
this.setState({ val2: n })
resetResult()
selectOperator(operatorVal, value1, value2)
}
render() {
const { n, operator, getNumber } = this.props
return (
<div>
<Display val={n == "" ? null : n} />
<Operator val={operator} />
{/* NUMBERS */}
<p data-n="1" onClick={this.displayNumber}>1</p>
<p data-n="2" onClick={this.displayNumber}>2</p>
<p data-n="3" onClick={this.displayNumber}>3</p>
{/* OPERATORS */}
<p data-sign="+" onClick={this.getOperator}>+</p>
<p data-sign="-" onClick={this.getOperator}>-</p>
<p data-sign="/" onClick={this.getOperator}>/</p>
<p data-sign="*" onClick={this.getOperator}>*</p>
<p onClick={this.getTotal}>equal</p>
<p onClick={this.deleteNumber}>clear</p>
</div>
)
}
}
export default Calculator
它基本上删除了数组中的最后一个元素(就像你在计算器上有一个清晰的函数一样)。
我得到的错误是数组中还有一个项目:
答案 0 :(得分:2)
你做的很好,但如果数组是空的怎么办? pop
将返回undefined
因此错误。
case 'CLEAR_NUMBER':
return [
...state
].pop()
修改强>
case 'CLEAR_NUMBER': {
if(state.length > 0) {
return [
...state
].pop()
}
return state;
}
答案 1 :(得分:2)
pop
返回已删除的元素,而不是修改后的数组。
你需要做
const newState = [...state];
newState.pop();
return newState;
或者,使用return state.slice(0, -1)
。
答案 2 :(得分:2)
您应该像这样使用以避免此类错误:
case 'CLEAR_NUMBER':
if ([...state].length > 1) {
return [...state].pop()
}
return [] // or return null, but not undefined ie. no explicit return