javascript - 循环浏览从状态映射的列表项 (javascript)
问题描述
我有一个包含嵌套数据的项目列表,这些数据保存在组件的状态中。我只是试图将项目的信息映射到屏幕上,同时允许用户使用下一个和上一个按钮循环浏览它们。
我的问题:当通过项目列表递增或递减时,应用程序出错。
如何将当前对象更改为下一个或上一个项目?
这是一个工作示例:https ://codesandbox.io/s/peaceful-albattani-g3r6u?file=/src/App.js
或者这里是整个 app.js:
import React, { useState } from "react";
import "./styles.css";
import {
ButtonDropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
Button
} from "reactstrap";
import "bootstrap/dist/css/bootstrap.min.css";
export default function App() {
const [dropdownOpen, setOpen] = useState(false);
const toggle = () => setOpen(!dropdownOpen);
const [currentIndex, setCurrentIndex] = useState({
itemIndex: 0,
locationIndex: 0
});
const [items, setItems] = useState([
{
item: 123,
locations: [
{ location: "loc1", count: 100 },
{ location: "loc2", count: 200 }
]
},
{
item: 456,
locations: [
{ location: "loc3", count: 200 },
{ location: "loc4", count: 300 }
]
},
{
item: 789,
locations: [
{ location: "loc5", count: 100 },
{ location: "loc6", count: 600 }
]
}
]);
const deleteItem = (item) => {};
const ddItemStyle = {
display: "flex",
flexDirection: "row",
alignItems: "center",
justifyContent: "center"
};
return (
<div className="App">
<ButtonDropdown isOpen={dropdownOpen} toggle={toggle}>
<DropdownToggle caret>locations</DropdownToggle>
<DropdownMenu>
{items[currentIndex.itemIndex].locations.map((location) => {
return (
<DropdownItem style={ddItemStyle}>
<Button
onClick={() => {
deleteItem(location.location);
}}
>
Delete
</Button>
: {location.location}{" "}
</DropdownItem>
);
})}
</DropdownMenu>
</ButtonDropdown>
<div style={{ height: "50%", width: "50%" }}>
Item: {items[currentIndex.itemIndex].item}
</div>
<Button
onClick={() => {
setCurrentIndex({
itemIndex: currentIndex.itemIndex + 1,
locationIndex: 0
});
}}
>
Prev
</Button>
<Button
onClick={() => {
setCurrentIndex({
itemIndex: currentIndex.itemIndex - 1,
locationIndex: 0
});
}}
>
Next
</Button>
</div>
);
}
解决方案
首先,您的上一个和下一个按钮需要交换。
此外,您需要注意不要越界;这就是您收到该错误的原因:
<Button
onClick={() => {
// out of bounds check
if(currentIndex.itemIndex <= 0) return;
setCurrentIndex({
itemIndex: currentIndex.itemIndex - 1,// decrement
locationIndex: 0
});
}}
>
Prev
</Button>
<Button
onClick={() => {
// out of bounds check
if(currentIndex.itemIndex >= items.length - 1) return;
setCurrentIndex({
itemIndex: currentIndex.itemIndex + 1,// increment
locationIndex: 0
});
}}
>
Next
</Button>
推荐阅读
- java - 无法在 IDE 中使用 AbstractProcessor
- c# - 从 SQL Server 事务中引发异常
- powershell - 导出所有公用文件夹的电子邮件地址
- laravel - 尝试 setDate() 时出现 Flatpickr 和 VueJS“self.config”错误
- sql - 无法使用 parse_date 解析 BigQuery 中的输入字符串
- laravel - 在 whereNotIn() laravel 上添加条件
- oauth-2.0 - 重新认证不需要 JWT 刷新令牌
- python - 如何检查语句是否匹配(Zip 函数)
- javascript - 为什么用 puppeteer 抓取数据总是从第一页提供数据?
- awk - 如何使用 awk 过滤换行符作为记录分隔符和字段分隔符