【发布时间】:2021-03-04 14:25:22
【问题描述】:
我正在使用反应钩子,我的组件中的状态。选项列表可供用户选择。我需要跟踪选择了哪些选项 - 请参阅状态中的“selectedArr”。
虽然这部分有效,但过滤 selectedArr 是错误的,如果我先选择选项中的第二项,则不会过滤?我不明白为什么。
如何跟踪选择了哪些选项并切换单个选项?
这是我的代码
const BarGraph = ({graphData, daysRange}) => {
const [optionsIndex, setOptionsIndex] = useState(0);
const [selectedArr, setSelectedArr] = useState([]);
const toggleActiveItem = (index) => {
//Update the option index
setOptionsIndex(index);
//Update selected options array
setSelectedArr([...selectedArr, index])
if(index === selectedArr[index]) {
//Prevent from adding multiple of the same index
setSelectedArr([...selectedArr])
//if index is equal to the selected array index
//removed the matched index from selected array
setSelectedArr(selectedArr.filter((i) => i !== index));
}
}
【问题讨论】:
-
你也能展示你的 JSX 吗?奇怪的是,您
setSelectedArr([...selectedArr, index])然后稍后使用if...//Prevent from adding multiple of the same index“撤消”更改。如果它不在数组中,为什么不只更新呢?我看不到任何保证if(index === selectedArr[index]) {是真的——你需要在整个数组中搜索那个索引。我会使用if (!selectedArr.includes(index)) setSelectedArr([...selectedArr, index]) else /* filter it out */。
标签: javascript arrays reactjs react-hooks