过滤数组 React Native 时出现错误错误

Getting error error when filtering array React Native

我正在 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>
  )
}

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

setSelected( selected.push(choice) )

使用

setSelected([...selected, choice])

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