【发布时间】:2020-12-25 13:23:09
【问题描述】:
我有一个包含嵌套数据的项目列表,这些数据以组件的状态保存。我只是试图将项目的信息映射到屏幕上,同时允许用户使用下一个和上一个按钮循环浏览它们。
我的问题:在项目列表中递增或递减时,应用程序出错。
如何将当前对象更改为下一项或上一项?
这是一个工作示例: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>
);
}
【问题讨论】:
标签: javascript reactjs