首页 > 解决方案 > 遇到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;
}

标签: javascriptreactjs

解决方案


推荐阅读