React states are not mapped in the correct order
P粉476547076
P粉476547076 2024-03-31 09:23:01
0
1
422

I have a Next.js project using Redux. In my store, I have a set of states that are updated via a Redux reducer. Basically a state array that I use a lot in some components.

In one of my reducers, I sort this array. The array is filled with objects and I sort them by specific properties. When I console.log the array it seems to be sorted fine.

In one of my components I mapped this sorting state. I've simplified the logic here.

names.map((p) => (
    <div key={p.name}>
      {p.firstname} {p.lastname}
    </div>
  ));

When the HTML is displayed, all elements are not in the correct order. The last few dozen div elements appear to be ordered, but the first dozen appear to be random.

For example, this is an array.

let names = [
    {
      "firstname": "Michael",
      "lastname": "Scott",
    },
    {
      "firstname": "Jim",
      "lastname": "Halpert",
    },
    {
      "firstname": "Dwight",
      "lastname": "Schrute",
    },
    {
      "firstname": "Pam",
      "lastname": "Beesly",
    },
    {
      "firstname": "Ryan",
      "lastname": "Howard",
    }
  ]

After sorting, console logging will return the expected results. This is the sorting function.

names = names.sort((a, b) => a.firstname.localeCompare(b.firstname))

The generated HTML should look like this.

Instead, the results are messed up for some reason. I suspect this is due to the Redux edit state, but I don't know why.

As far as I know this is a widespread bug and I'll be happy to provide any additional context if my code is oversimplified. Any answers would be greatly appreciated, but any answers that help narrow down where the problem lies would be especially helpful.

P粉476547076
P粉476547076

reply all(1)
P粉765684602

I am using Redux reducer to sort an array. Although the console log is correct, the elements are displayed in the wrong order. While I still don't know why this happens, the solution is to not sort the content in the reducer.

In Redux you should sort things via selectors instead of directly By sorting things in my selector instead of directly in my reducer the problem solved itself.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template