javascript - 遇到TypeError:尝试使用react creatable select使用搜索栏时值不可迭代
问题描述
我正在开发一个反应应用程序,但是当我尝试使用反应可创建选择在搜索栏中输入一个值时遇到错误,使用它的值旁边的 x 按钮(不是最右边的 x 按钮)删除它,然后输入另一个值. 如何防止这个错误?
TypeError: values is not iterable handleBlur [as onBlur] setValues(removeDuplicates([...values, createOption(inputValue)], 'value'));
谢谢您的帮助。
import PropTypes from "prop-types";
import { useState } from 'react';
const createOption = (label) => ({
label,
value: label,
});
const propTypes = {
initialValues: PropTypes.array,
onSearch: PropTypes.func,
debug: PropTypes.bool
};
const removeDuplicates = (myArr, prop) => {
return myArr.filter((obj, pos, arr) => {
return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;
});
}
export const useSearchBar = (props) => {
PropTypes.checkPropTypes(propTypes, props, "property", "useSearchBar");
let {
initialValues = [],
onSearch,
loading
} = props;
// But use the users state if provided
const [inputValue, setInputValue] = useState('');
const [values, setValues] = useState(initialValues);
const handleBlur = (event) => {
if(!inputValue || !inputValue.trim()) {
return;
}
setValues(removeDuplicates([...values, createOption(inputValue)], 'value'));
setInputValue('');
};
const handleValueChange = (val, actionMeta) => {
setValues(val);
};
const handleInputValueChange = (inputValue) => {
if(!inputValue) {
return;
}
const re = /^[\d,\s]+$/;
if (re.test(inputValue)) {
setInputValue(inputValue.trim());
}
};
const handleKeyDown = (event) => {
if (!inputValue) return;
switch (event.key) {
case 'Enter':
case 'Tab':
setInputValue('');
setValues(removeDuplicates([...values, createOption(inputValue)], 'value'));
event.preventDefault();
break;
default:
}
};
api.getSearchBarProps = userProps => ({
...props,
components,
value: values,
onChange: handleValueChange,
inputValue,
onKeyDown: handleKeyDown,
onInputChange: handleInputValueChange,
onBlur: handleBlur,
delimiter: ",",
placeholder: "Search Transaction(s)...",
loadingMessage: "Loading...",
loading
});
return api;
}
解决方案
推荐阅读
- json - 如何表明对象的每个键都具有相同的类型?
- ios - 如果我在我的 iOS 应用程序中使用一小部分歌曲作为闹钟播放,是否会被视为版权?我的应用会因侵犯版权而被下架吗?
- go-cd - GO CD - 在失败时获取材料
- regex - 正则表达式重写规则添加具有相同长度的前导零
- android-intent - Chrome 操作系统 - 安装的 PWA 不会从使用 Android 意图的主机链接启动(深度链接)
- arrays - 在 PostgreSQL 中查询 JSON 对象数组中的条件
- javascript - 为什么这个循环重复输出数据?
- ldap - 将角色名称映射到角色
- android - 在 Android Studio 中更改 Autosuggestbox 的颜色
- c# - C# ServerManager 在 Windows 7 上泄漏内存