简体   繁体   中英

How to set separate states for mapped elements in React?

I am trying to create a button for every element in a list using map. However, each button should change that element's enable status independently but right now they share the same enable state. I am not sure what the alternative to hard coding an x amount of states would be so I am wondering if there is a way to either mass produce states for mapped elements or if this can be done through the one state I created while using a different hook.

const [enableS, setEnableS] = useState(true);
const list = [x,y,z]
return (<>
  list.map(() => 
    <button onClick={()=>setEnableS(!enableS)}>Enable/Disable</button>
  )
  </>);

So your going to need to store the 3 states your looking for separately in an array.

I had a similar scenario and I used an array like this.

// To store a series of values in one const useState.
const [form, setForm] = useState([1, 15, 2, 100, 2, 2, 5, 5]);
...
function formCallback(val, index) {
    let newArray = form.map(x => x)
    newArray[index] = val
    //mapped twice to avoid bug.
    setForm(newArray.map(x => x))
    console.log(form)
    }
    

in your scenario I would try

const [enableS, setEnableS] = useState([true,true,true]);

function enableSCallback(oldBool, index) {
    let newArray = form.map(x => x)//Holding the values in a temporary array.
    newArray[index] = !oldBool//Adjusting the value you want flipped.
    setEnableS(newArray.map(x => x))//Updating the state with these new values. 
    }
return(
list.map(
(a,b) =>
<button onClick = {enableSCallback(a,b)}</button>
))

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