The issue lies in the ghost tags, they are at the highest level, so they are expected to retain the key.
if you do need the ghost tags to exist you could instead use <React.Fragment key={...your key}>
as opposed to ghost tags
import React from 'react'
class Body extends React.Component{
constructor(props){
super(props)
this.state = {
counters:[
{id:1, value:0},
{id:2, value:0},
{id:3, value:0},
{id:4, value:0},
],};
}
render(){
return(
<>
<nav className="navbar navbar-light bg-light">
<a className="navbar-brand" href="/#">Navbar
<span className='badge badge-pill badge-secondary m-3'>{this.state.counters.filter(counter => counter.value > 0).length}</span>
</a>
</nav>
<div className='container'>
<button className='btn btn-primary btn-sm' onClick={()=>this.handleReset()}> Reset</button>
{this.state.counters.map((counter)=>{
return(
<div key={counter.id>
<span className={this.changeClass(counter)}>{counter.value ===0 ? 'zero':counter.value}</span>
<button className='btn btn-secondary' onClick={()=> this.handleIncrement(counter)} >Increment</button>
<button className='btn btn-danger m-2' onClick ={()=> this.handleDelete(counter)} >Delete</button>
</div>
)
})}
</div>
</>
)
}
changeClass(counter){
let classes = 'btn btn-sm m-2 btn-'
classes += counter.value === 0 ? 'warning': 'primary'
return classes
}
handleIncrement(counter){
const counters = [...this.state.counters]
const index = counters.indexOf(counter)
counters[index].value ++
this.setState({counters})
}
handleDelete(counter){
const counters = this.state.counters.filter(c=> c.id !== counter.id )
this.setState({counters})
}
handleReset(){
const counters = this.state.counters.map(counter=>{
counter.value = 0
return counter
} )
this.setState({counters})
}
}
export default Body
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…