Reactjs React error空数组没有初始值

Reactjs React error空数组没有初始值,reactjs,Reactjs,这是一个计数器组件,所有按钮意味着增加按钮减量按钮和删除btn 这是我的截图 但问题是,当我点击删除按钮时,当我转到最后一个删除按钮时,它将被删除 它开始抛出错误 这是我的密码 class Counters extends Component { state={ counters:[ {id:1, value:0}, {id:2, value:0}, {id:3, value:0},

这是一个计数器组件,所有按钮意味着增加按钮减量按钮和删除btn 这是我的截图

但问题是,当我点击删除按钮时,当我转到最后一个删除按钮时,它将被删除

它开始抛出错误 这是我的密码

class Counters extends Component {
    state={
        counters:[
            {id:1, value:0},
            {id:2, value:0},
            {id:3, value:0},
            {id:4, value:0}
        ],
       

    }
    handleIncrement=counter=>{
        const counters =[...this.state.counters];
        const index = counters.indexOf(counter);
        counters[index]={...counter}
        counters[index].value++;
        this.setState({counters})
    }
    handleDecrement=counter=>{
        const counters =[...this.state.counters];
        const index = counters.indexOf(counter);
        counters[index]={...counter}
        counters[index].value = counters[index].value > 0 ? counters[index].value-1:0;
        this.setState({counters})
    }
    handleDelete=(counterid)=>{
      const counters = this.state.counters.filter(m=>m.id !== counterid)
      this.setState({counters})
    }
    handleReset=()=>{
        const counters = this.state.counters.map(m=>{ 
            m.value = 0;
             return m
        })
        this.setState({counters})

    }
    
    render() {
        
        return (
            <div>
                <h1>{this.state.counters.reduce((a,b)=>({value:a.value+b.value})).value}</h1>
                <button onClick={this.handleReset} className="btn btn-secondary btn-sm">RESET</button>
           {this.state.counters.map(m=>
           <Counter key={m.id} 
             id={m.id} getDelete={this.handleDelete}
              onIncrement={this.handleIncrement}
              onDecrement={this.handleDecrement}
              counter={m}
              >
           
              
           </Counter>) }


            </div>

        );
    }
}
类计数器扩展组件{
陈述={
计数器:[
{id:1,值:0},
{id:2,值:0},
{id:3,值:0},
{id:4,值:0}
],
}
handleIncrement=计数器=>{
常量计数器=[…this.state.counters];
const index=计数器。indexOf(计数器);
计数器[索引]={…计数器}
计数器[索引]。值++;
this.setState({counters})
}
handleDecrement=计数器=>{
常量计数器=[…this.state.counters];
const index=计数器。indexOf(计数器);
计数器[索引]={…计数器}
计数器[index]。值=计数器[index]。值>0?计数器[index]。值-1:0;
this.setState({counters})
}
handleDelete=(计数器ID)=>{
const counters=this.state.counters.filter(m=>m.id!==counterid)
this.setState({counters})
}
handleReset=()=>{
const counters=this.state.counters.map(m=>{
m、 数值=0;
返回m
})
this.setState({counters})
}
render(){
返回(
{this.state.counters.reduce((a,b)=>({value:a.value+b.value})).value}
重置
{this.state.counters.map(m=>
) }
);
}
}

Reduce采用两个参数,函数和初始值。由于要将阵列缩减为单个对象,因此需要提供一个空选项,以开始:

this.state.counters.reduce((a,b)=>({value:a.value+b.value}),{value:0})。value

不过,将其减少到一个数字可能会更干净,即

this.state.counters.reduce((总和,当前)=>sum+current.value,0)