Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

javascript - React Array Reload function

i create a button that delete element from array and its work good! but im trying to add another button that reload the array again and show the original with the deleted elements

i want to clone th array and use the handlereload to show the full elements again without refresh the page or use the simple reload window function

this is with this.props in other component

enter image description here

after delete element enter image description here

now i click on reload the button is work but is return the element undefind with error enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]);
  }
  
  // ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...