【问题标题】:React JS Toggle Selected ItemReact JS 切换所选项目
【发布时间】: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


【解决方案1】:
const toggleActiveItem = (index) => {
    
    if(selectedArr.includes(index)){
      setSelectedArr(selectedArr.filter((i) => i !== index)) 
    } else {
     setSelectedArr([...selectedArr, index]) 
    }

    setOptionsIndex(index)
}

【讨论】:

  • 就是这样!妈的,我哪里错了?而不是 if 语句中的等于 .includes 代替?
  • 你做错了条件和 if 语句
猜你喜欢
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 2011-09-19
  • 2018-09-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 2021-02-24
相关资源
最近更新 更多