反应数组重载功能

时间:2020-12-30 14:10:41

标签: javascript arrays reactjs function

我创建了一个从数组中删除元素的按钮,效果很好! 但我试图添加另一个按钮,再次重新加载数组并显示带有已删除元素的原始元素

我想克隆数组并使用handlereload再次显示完整元素 无需刷新页面或使用简单的重新加载窗口功能

这是在其他组件中的 this.props

enter image description here

删除元素后 enter image description here

现在我点击重新加载按钮工作但返回元素未定义 有错误 enter image description here

1 个答案:

答案 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]);
  }
  
  // ...
}
相关问题