javascript - 过滤数组 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
一个数组时,它返回你推送到数组的内容,而不是你调用函数的数组。所以而不是
setSelected( selected.push(choice) )
利用
setSelected([...selected, choice])
这会将 添加choice
到当前selected
数组的末尾,然后使用钩子更新它。
推荐阅读
- python - Python 正则表达式:拆分 vsv 列
- javascript - 如何加快 MongoDB 视图的计数
- netcat - 如何让 netcat 等待来自客户端的响应?
- r - R - 根据另一列中的另一行向下填充一列的行
- python-3.x - RingCentral API CallLog 在不同时区给出响应
- php - 致命错误:未捕获的错误:第 23 行的 Class 'User' C:\xampp\htdocs\gallery\admin\includes\admin_content.php
- eclipse - IntelliJ 自定义数据视图等效于 Eclipse?
- clojure - 如何使用 clj 工具 AOT 编译单个 clojure 文件?(没有 deps.edn 文件)
- elasticsearch - 我可以从 Elasticsearch/X-pack 中的 Forecast API 检索数据吗
- ios - 当应用程序终止或未运行时,从iOS中的AppStore更新应用程序时是否有任何回调?