If you want to be able to restore the original state, you need to keep it stored somewhere.
A way of doing it could be:
Class component:
class MyClassComponent extends React.Component {
constructor() {
this.initCounter = [
{ id: 1, value: 3, img: '' },
{ id: 2, value: 2, img: '' },
{ id: 3, value: 0, img: '' },
{ id: 4, value: 0, img: '' }
];
this.state = {
counter: [...this.initCounter]
}
this.handleDelete = this.handleDelete.bind(this);
this.handleReload = this.handleReload.bind(this);
}
handleDelete(id) {
this.setState({
...this.state,
counter: this.state.counter.filter(item => item.id !== id)
})
}
handleReload() {
this.setState({
...this.state,
counter: [...this.initCounter]
})
}
// ...
}
Functional component with hooks
const initCounter = [
{ id: 1, value: 3, img: '' },
{ id: 2, value: 2, img: '' },
{ id: 3, value: 0, img: '' },
{ id: 4, value: 0, img: '' }
];
const MyFunctionalComponent = () => {
const [counter, setCounter] = useState([...initCounter]);
const handleDelete = (id) => {
setCounter(counter.filter(item => item.id !== id));
}
const handleReload = () => {
setCounter([...initCounter]);
}
// ...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…