[英]Why does useState not increment
I'm trying to implement useState to store an incrementing value.我正在尝试实现 useState 来存储递增值。 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.每当您想根据 state 的先前值更新 state 时,您必须在 setState 中使用 function。
ie IE
setCardsIndex((prevValue) => prevValue + 1)
Docs: https://reactjs.org/docs/hooks-reference.html#functional-updates文档: 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);}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.