【问题标题】:Getting error error when filtering array React Native过滤数组 React Native 时出现错误错误
【发布时间】:2021-04-09 20:07:11
【问题描述】:

我正在 React Native 中构建一个简单的复选框组件,我正在尝试制作一些脚本来添加和删除选定选项数组中的选定选项。 我正在使用 Array.filter() 函数来检查一个项目是否在数组中 - 但是我收到了这个错误:

selected.filter is not a function. 
(In 'selected.filter(function (c) {
      return c === choice;
})', 'selected.filter' is undefined)

这是我的代码:

const Select = ({ multichoice, isMultiple }) => {
  const [selected, setSelected] = useState([])

  const includes = choice => (
    selected.filter( c => c === choice ).length
  )

  const toggleSelected = choice => { 
    if ( includes(choice) ) setSelected( selected.filter( c => c != choice ) )
    else setSelected( selected.push(choice) )
  }

  return (
    <View style={styles.selectContainer}>
      {multichoice.map(choice =>
        <Option choice={choice} toggleSelected={toggleSelected} selected={includes(choice)}/>
      )}
    </View>
  )
}

【问题讨论】:

    标签: javascript reactjs react-native babeljs


    【解决方案1】:

    当您在数组上调用 .push 时,它会返回您推送到数组的内容,而不是您在数组上调用函数的内容。所以不是

    setSelected( selected.push(choice) )
    

    使用

    setSelected([...selected, choice])
    

    这会将choice 添加到当前selected 数组的末尾,然后使用钩子更新它。

    【讨论】:

    • 非常感谢,我错过了 - 它似乎仍然无法正常工作。它现在给出错误最大更新深度超出
    • 如果是这种情况,那么我们需要看到的不仅仅是您在此处发布的代码。我建议写一个新问题,因为这超出了当前问题的范围。
    • 现在很担心,看来我已经解决了(主要是在您的帮助下)非常感谢!
    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 2019-02-16
    • 2019-10-05
    • 2020-07-27
    • 2018-01-16
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多