Intento ordenar mi matriz en reversa y uso la función reverse()
pero no afecta la vista. Debo cambiar el archivo y guardarlo, luego puedo ver los cambios.
Artículos.js:
import { useState } from "react"; const Items = (props) => { const [myArray, setMyArray] = useState([ { pId: 1, title: "P 1", }, { pId: 2, title: "P 2", }, { pId: 3, title: "P 3", }, { pId: 4, title: "P 4", }, ]); const handleSort = () => { console.log("before", myArray); setTimeout(() => { setMyArray(myArray.reverse()); console.log("after", myArray); }, 500); }; return ( <div> {myArray.map((a) => ( <span key={a.pId} className="m-3"> {a.title} </span> ))} <button onClick={handleSort}>reverse</button> </div> ); }; export default Items;
Estás invirtiendo una matriz de objetos. use el operador de propagación para distribuir los elementos de su matriz.
Esto debería funcionar bien.
let myArray = [ { pId: 1, title: "P 1", }, { pId: 2, title: "P 2", }, { pId: 3, title: "P 3", }, { pId: 4, title: "P 4", } ] console.log([...myArray].reverse());