为什么useState不会递增

3

我正在尝试使用useState来存储一个递增的值。当我尝试递增该值时,它并没有更新。我已经尝试手动将该值设置为特定的数字,并且这样做确实有效。出了什么问题?

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

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

你能进行一些逐步调试或在实际事件处理程序中添加console.log吗?当你调用setCardsIndex时,cardsIndex是什么? - Evert
我尝试运行console.log,但当onSwipedRight和Left函数运行时,该值根本没有增加。 - chackerian
你从哪里获取 Card 组件? - Samathingamajig
这不相关。 - chackerian
2个回答

8

这是一个新的要求吗? - chackerian
1
不,这是根据先前状态值更新状态的推荐方式。 - Mubashir Hassan
一些教程使用了我添加的方法。我猜想那种方式现在可能不再被允许。 - chackerian
你可以这样做,但在这种情况下,不能保证你会得到状态的最新值。 - Mubashir Hassan
这种情况至少从2019年开始就存在了,即使是类组件也是如此。https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous - Nice Books

0

只需更改:

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

收件人:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接