无法从react-select AsyncSelect下拉列表中获取所选值

时间:2020-06-15 09:44:20

标签: reactjs react-hooks react-select

成功从服务器获取数据 但是在选择选项时,它不会被选择并显示在下拉菜单中。 而且值也不会存储在selectedOption中

import AsyncSelect from 'react-select/async';

const Register = (props) => {
  const [selectedOption, setSelectedOption]=useState("");

  const loadOptions = async (inputValue, callback) => {

      const response = await fetch('http://localhost:8080/api/user_location'+inputValue)
      const json = await response.json();
      callback(json.map(i=>({label:i.vdc+', '+i.district, value:i.vdc_id})));
  }

  const onChangeSelectedOption = (e) => {
    const selectedOption = e.target.value;
    setSelectedOption(selectedOption);
  };

  return (
         <AsyncSelect
           value={selectedOption}
           onChange={onChangeSelectedOption}                    
           loadOptions={loadOptions}
           defaultOptions={false}
           placeholder="Your Place"
         />
 );
};

谢谢!

1 个答案:

答案 0 :(得分:1)

onChange事件返回selected object,而不是event object

const onChangeSelectedOption = (e) => {
    console.log(e); // <---- this will be selected object not event
    const selectedOption = e.value; // <--- you can get value from object directly
    setSelectedOption(selectedOption);
};

工作演示:

Edit react-codesandboxer-example