您好,圣诞快乐,
我有一个包含嵌套数据的项目列表,这些数据以组件状态保存。我只是试图将项目的信息映射到所有屏幕,同时允许用户使用下一个和上一个按钮在它们之间循环。
我的问题:在项目列表中增加或减少时,应用程序会出错。
问题:如何将当前对象更改为下一个或上一个项目?
这是一个工作示例: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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句