简体   繁体   中英

How to decleare multiple state variables using loop - react state hook

I want to declare some state variable like: processId_1, processId_2, processId_3..... processId_n.

const [processId, setProcessId] = useState(0) ; I just want to use loop on the code to declare these variable. Something like that:

for (let index = 0; index < 30; index++) {
    const [processId["".concat("_",index)], setProcessId]["".concat("_",index)] = useState(0);
    
}

在此处输入图像描述

I also want to send them as props. How to do that.

It is possible to create an array of these states. So code would look like this:

const [processIds, setProcessIds] = useState([
    {
      id: '1',
      name: 'processId 1'
    },
    {
      id: '2',
      name: 'processId 2'
    }
]);

const handleClick = () => {
  setProcessIds([...processIds].map(pr => {
        if(pr.id === '1') {
          return {
            ...pr,
            name: 'processId is edited'
          }
        }
        else return pr;
      }))
}

<button onClick={handleClick}>
</button>

UPDATE:

It is possible to add keys into object dynamically like this:

const  obj = {};

for (let i = 10; i <= 20; i++) {
    obj['processId_' + i] = 0;
} 

An example:

 const obj = {}; for (let i = 10; i <= 20; i++) { obj['processId_' + i] = 0; } console.log(obj)

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