简体   繁体   中英

Passing associative array as props not working

I have a React application which handles rooms and their statistics.

Previously, I had the code set up to pass as props to the next component:

  • the raw statistics (not a concern for the question)
  • an array of all the rooms set up as follows

    使用数字索引启动数组

I figured it would be simpler for me, though, to have the list of all rooms as an associative array where the keys of each element is the same as the ID it contains. To do that, I utilized a code similar to this in a for loop:

roomsList[rooms[v].ID] = rooms[v];

So that the result would be:

[a001: {...}, a002: {...}, ...]

I then proceeded to pass this style of array, and not the standard one with a numeric index, as a prop to the next component as such:

<StatsBreakdown stats={computedStats.current} roomsList={roomsList} />

BUT

Now, the next component sees that prop as an empty array.

空数组的示例 Even more weirdly, if I initialize that roomsList array with a random value [0] and then do the same process, I end up with: 使用随机数初始化的数组示例

I cannot cycle through the array with .map, and, according to JS, the length is actually 0, it's not only Google Chrome.

Is there something I'm missing about the way JSX, JS or React work?

Your original roomsList was an array of objects , whose indices were 0,1,2 etc. roomsList[rooms[v].ID] = rooms[v]; implies you are inserting elements not using a number but an alphanumeric string. Hence your resulting array is no longer an array but an object .

So we can cycle over the object using Object.keys() .

const renderRoomDets = Object.keys(roomsList).map(room => {
  roomOwner = roomsList[room].owner_id;
  return (
    <div>
      <p>{`Room Owner ${roomOwner}`}</p>
    </div>
  );
});

But I believe your original form is ideal, because you are reaping no special benefits from this notation.

A better alternative maybe using .find() or .findIndex() if you want iterate over an array based on a specific property.

const matchedRoom = roomsList.find(room => room.ID === 'Srf4323')

Iterate the new array using its keys not indexes.

Or even better store your data in an actual object instead of an array since you're using strings for ids.

First define your object like so:

let data = {};

Then start adding records to it. I'd suggest deleting the ID attribute of the object since you're storing it in the key of your record, it's redundant, and it won't go anywhere unless u delete the entry.

data[ID] = row;

To delete the ID attribute (optional):

row.ID = null;
delete row.ID;

Then iterate through it using

for(let key in data){}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM