数组反转不影响

array reverse dosen't effect

我尝试对我的数组进行反向排序,我使用了 reverse() 函数,但它不影响查看。我必须更改文件并保存,然后我才能看到更改。

Items.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;

您正在反转对象数组。使用展开运算符展开数组的元素。

这应该可以正常工作。

  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());