简体   繁体   中英

Why does useState not increment

I'm trying to implement useState to store an incrementing value. When I try incrementing the value it doesn't update it. I have tried manually setting the value to a specific number and this does work. What is wrong?

const [cardsIndex, setCardsIndex] = useState(0);

       <Card style={[styles.card, styles.card1]} key={index}
          onSwipedRight={(event) => { setCardsIndex(cardsIndex+1);}}
          onSwipedLeft={(event) => { setCardsIndex(cardsIndex+1);}}
       >

Whenever you want to update the state based on previous value of the state then you kust use a function in setState.

ie

setCardsIndex((prevValue) => prevValue + 1)

Docs: https://reactjs.org/docs/hooks-reference.html#functional-updates

Just change:

onSwipedRight={(event) => { setCardsIndex(cardsIndex+1);}}
onSwipedLeft={(event) => { setCardsIndex(cardsIndex+1);}}

to:

onSwipedRight={(event) => {() => { setCardsIndex(cardsIndex =>cardsIndex+1);}}
onSwipedLeft={(event) => { () => { setCardsIndex(cardsIndex =>cardsIndex+1);}}}

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