javascript - Cómo devolver elementos Reaccionar

CorePress2024-01-24  11

Pido tu ayuda. Tengo un código de trabajo y dos botones. Uno elimina el primer elemento de la matriz, el segundo, el último elemento. Cómo utilizar la función "Restaurar" botón para restaurar (restaurar) todos los elementos.

import logo from './logo.svg';
import React, {useState} from 'react';
import './App.css';

function App() {
    let [array, changedArray] = useState([
{
id: 1,
title:'title 1',
price:1
},
{
id: 2,
title: 'title 2',
price: 2
},
{
id:3,
title: 'title 3',
price: 3
}
)]

 function removeFirstElement () {
 let newArray = [...array];
 newArray.shift();
 changedArray(newArray);
}

function removeLastElement() {
let newArray = [...array];
newArray.pop();
changedArray(newArray)
}

return(
<div>
<ul>{array.map(el =><li>{el.title} {el.price}</li>)}</ul>
<button onClick={removeFirstElement}>Delete first element</button>
<button onClick={removeLastElement}>Delete last element</button>
<button>Restore</button>
</div>
);
}

export default App;


------------------------------------

Lo que podrías hacer es almacenar la matriz inicial en una referencia. Cuando haces clic en el botón restaurar, puedes configurar tu estado con esa referencia.

let [array, changedArray] = useState([...])
let initialValue = useRef(array);

const onRestore = () => {
    changedArray(initialValue.current);
};

<button onClick={onRestore}>Restore</button>



------------------------------------

SíPuede usar el evento onClick en el botón de reinicio y llamar a la función que recargará la página. Eso hará el trabajo.

 const restoreHandler = () => {
   location.reload()
} 

<button onClick={restoreHandler}>Restore</button>
Compartir mejorar esta respuesta Seguir Respondido

26 de marzo de 2021 a las 15:59

Daniel

Daniel

1

Su guía para un futuro mejor - libreflare
Su guía para un futuro mejor - libreflare