首页 > 解决方案 > 过滤数组 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>
  )
}

标签: javascriptreactjsreact-nativebabeljs

解决方案


当你调用.push一个数组时,它返回你推送到数组的内容,而不是你调用函数的数组。所以而不是

setSelected( selected.push(choice) )

利用

setSelected([...selected, choice])

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


推荐阅读