我创建了一个从数组中删除元素的按钮,效果很好! 但我试图添加另一个按钮,再次重新加载数组并显示带有已删除元素的原始元素
我想克隆数组并使用handlereload再次显示完整元素 无需刷新页面或使用简单的重新加载窗口功能
这是在其他组件中的 this.props
答案 0 :(得分:0)
如果您希望能够恢复原始状态,则需要将其保存在某个地方。 一种方法可能是:
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]
})
}
// ...
}
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]);
}
// ...
}