简体   繁体   中英

ByReference useState

Using mui-material, i'm collapsing a table row using this line

<Collapse in={"open"+row.name} timeout="auto" unmountOnExit>

I have a useState

const [openOne, setOpenOne] = useState(false)

during the .map iteration, the first row.name would be One so in the collpase it would create like in={openOne}

My problem is how do I reference the {"open"+row.name} which would be {openOne} to the useState openOne ?

You should use a different approach.

Maybe instead of using a different useState for each item, you should use one that hold the values for all of them.

const [openRows, setOpenRows] = useState(()=>{
   // replace allRows with the list of rows you have
   allRows.reduce((acc, {name})=>({
     ...acc,
     [name]: false
   }),{});
});

now you can use

<Collapse in={openRows[row.name]} timeout="auto" unmountOnExit>

and to set a row, you can do

setOpenRows((currentOpen) => ({
  ...currentOpen,
  'one': true  // or [row.name]: true if you are using it in a dynamic way
}));

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