首页 > 解决方案 > 在用户输入时加载异步选项的 react-select 动态下拉列表

问题描述

我是 React 新手,我正在尝试合并 2 个不同的功能。一种动态表单,您可以在其中添加和/或删除输入,以及一个带有异步反应选择的表单,您可以在其中开始输入单词,选项会出现并根据 API 源进行过滤(例如,基于连接的用户)

我几乎完成了(我认为)但是:

当我开始输入时,我正确地看到了我的选项......并且选项被正确过滤但是当我点击一个项目(选择这个项目)时,我得到一个错误。

我得到的错误是Cannot read property 'name' of undefined,但我不明白,我不确定这是我遇到的唯一问题。我不知道如何让我的选择正确地被选中并正确放入我的对象数组中(inputFields

这是我尝试混合的两种不同的来源(它们都完美地独立工作)

React-Select Async 下拉列表:https ://stackblitz.com/edit/react-select-async-component?file=index.js 动态表单字段:https ://www.youtube.com/watch?v=zgKH12s_95A

感谢您帮助我了解问题所在!

这是我的代码:

function AsyncDynamicForm(props) {
  const [inputFields, setInputFields] = useState([
    { firstName: '' },
  ]);
  const [inputValue, setValue] = useState("");


  const handleChangeInput = (index, event) => {
    const values = [...inputFields];
    values[index][event.target.name] = event.target.value;
    setInputFields(values);
  };

  const AddFields = () => {
    setInputFields([...inputFields, { firstName: '' }]);
  };

  const RemoveFields = (index) => {
    const values = [...inputFields];
    values.splice(index, 1);
    setInputFields(values);
  };


  const loadOptions = (inputValue) => {
    return fetch(
      `http://127.0.0.1:8000/api/Objects/?q=${inputValue}`
    ).then((res) => res.json());
  };
    

  const handleInputChange = (value) => {
    setValue(value)
  };
  
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("inputFields", inputFields); // Nothing for now
  };


  return (
    <div>
        <Container>
          <Form onSubmit={handleSubmit}>
            {inputFields.map((inputField, index) => (
              <div key={index}>
                <Form.Field inline>
                  <AsyncSelect
                    name="firstName"
                    value={inputField.firstName}
                    onChange={(event) => handleChangeInput(index, event)}
                    cacheOptions
                    defaultOptions
                    getOptionLabel={(e) => e.name.toString()}
                    getOptionValue={(e) => e.id}
                    loadOptions={loadOptions}
                    onInputChange={handleInputChange}
                  />
                </Form.Field>
                <Button.Group basic size="small">
                  <Button icon="add" onClick={() => AddFields()} />
                  <Button
                    icon="x"
                    onClick={() => RemoveFields(index)}
                  />
                </Button.Group>
              </div>
            ))}
          
            <Button type="submit" onClick={handleSubmit}>
              click
            </Button>
          </Form>
        </Container>
    </div>
  );
}

export default AsyncDynamicForm

标签: javascriptreactjsformsapireact-select

解决方案


文档在这里非常有用。该onChange道具采用具有特定签名的方法。

const onChange = (option, {action}) => {
  /* The `option` value will be different, based on the Select type
   * and the action, being one of `option`, an array of `option`s
   * (in the instance of a multiselect), `null` (typical when clearing
   * an option), or `undefined`.
   * What you actually get will depend on the `action` the select passes,
   * being one of:
   * - 'select-option'
   * - 'deselect-option'
   * - 'remove-value'
   * - 'pop-value'
   * - 'set-value'
   * - 'clear'
   * - 'create-option'
   */
   // example uses the `useState` hook defined earlier
   switch (action) {
     case 'select-option',
     case 'remove-value',
     case 'clear':
       setColor(option);
       break;
     default:
       // I'm not worried about other actions right now
       break;
   }
};

请记住,React-Select 将value其视为整个option对象,而不仅仅是option您在getOptionValue. 如果您正在考虑设置一个真正的表单“值”,您可能会以某种方式包装 Select 来处理它。

React-Select 非常强大,也非常复杂。文档是您的朋友。在尝试我还不完全理解的功能时,我发现在 CodeSandbox 中玩耍很有帮助。


推荐阅读