在 React 中,当你按下“previous”按钮时,上一个索引没有更新的原因可能是由于你没有正确更新状态。
以下是一个可能的解决方法,其中包含一个简单的代码示例:
import React, { useState } from 'react';
const App = () => {
const [currentIndex, setCurrentIndex] = useState(0);
const data = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];
const handlePrevious = () => {
if (currentIndex > 0) {
setCurrentIndex(currentIndex - 1);
}
};
const handleNext = () => {
if (currentIndex < data.length - 1) {
setCurrentIndex(currentIndex + 1);
}
};
return (
{data[currentIndex]}
);
};
export default App;
在上面的示例中,我们使用 useState
钩子来创建一个名为 currentIndex
的状态变量,初始值为 0。然后,我们创建一个 data
数组,其中包含要显示的项目。
handlePrevious
函数用于处理“previous”按钮的点击事件。它首先检查 currentIndex
是否大于 0,如果是,则将 currentIndex
减 1,并通过调用 setCurrentIndex
更新状态。
handleNext
函数用于处理“next”按钮的点击事件。它首先检查 currentIndex
是否小于 data
数组的长度减 1,如果是,则将 currentIndex
加 1,并通过调用 setCurrentIndex
更新状态。
最后,我们在 JSX 中显示 data[currentIndex]
,以显示当前索引对应的项目。
这样,当你按下“previous”按钮时,上一个索引将会正确更新。
上一篇:按下取消时时间选择器不关闭
下一篇:按下热键后随机延迟