简体   繁体   English

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

[英]Getting error error when filtering array React Native

I am building a simple checkbox component in React Native, I am trying to make some script to add and delete selected choice from an array of selected choices.我正在 React Native 中构建一个简单的复选框组件,我正在尝试制作一些脚本来从一组选定的选项中添加和删除选定的选项。 I am using the Array.filter() function to check whether an item is in the array - however I get this error:我正在使用Array.filter() function 检查一个项目是否在数组中 - 但是我收到此错误:

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

Here is my code:这是我的代码:

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>
  )
}

When you call .push on an Array, it returns what you pushed to the array, not the what the array you called the function on.当您在数组上调用.push时,它会返回您推送到数组的内容,而不是您调用 function 的数组。 So instead of所以而不是

setSelected( selected.push(choice) )

use利用

setSelected([...selected, choice])

This will add the choice to the end of your current selected array and then update that with the hook.这会将choice添加到当前selected数组的末尾,然后使用钩子更新它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM