react-select中AsyncSelect的'defaultInputValue'属性?

The 'defaultInputValue' prop of AsyncSelect in react-select?

import AsyncSelect from 'react-select/async';

<AsyncSelect
              cacheOptions
              isClearable={false}
              defaultInputValue={doctor.name}
              loadOptions={async (search, callback) => {
                const doctors = await fetchDoctors(search);
                const doctorsList = doctors.map(item => ({
                  ...item,
                  label: item.doctorName,
                  value: item.doctorName,
                }));
                callback(doctorsList);
              }}
              backspaceRemovesValue
              placeholder='Search for a doctor...'
              onChange={async (newVal) => {
                const updatedOrder = { ...order };
                updatedOrder.doctorId = newVal.id;
                if (newVal.organization) {
                  updatedOrder.organization = newVal.organization;
                } else {
                  updatedOrder.organization = '';
                }
                updateOrderRemote(updatedOrder, newVal);
              }}
/>

初始渲染中的 'defaultInputValue' 属性通过未定义或空字符串或字符串传递。

但是,在 doctor.name 可用一段时间后,defaultInputValue 不会更新,因此会保持初始渲染时的值。

您有两个选择: 1- 您可以使整个 <AsyncSelect {...props} /> 的渲染以 doctor.name 的可用性为条件(我假设是一种状态)。我想这对你来说并不理想。 2- 你应该传递 inputValue 属性而不是 defautInputValue。因为据我所知,默认值只在第一次渲染时传递。因此,您还需要更改 onChange 道具的功能,以更改用作初始值的状态

按照 Ardalan Nahavendi 的建议,我走了当地的国道。

但是触摸 inputValue 道具会导致另一组问题,所以我选择了 value 道具。

代码:

import AsyncSelect from 'react-select/async';

  const [doc, updateDoctor] = useState({ label: doctor?.name, value: doctor?.name });

  useEffect(() => {
    if (doctor.doctorName) { //at initial render the doctor prop gets the 'doctorName' key 
      updateDoctor({ label: doctor?.doctorName, value: doctor?.doctorName });
    } else {
      updateDoctor({ label: doctor?.name, value: doctor?.name });
    }
  }, [doctor]);

<AsyncSelect
  cacheOptions
  isClearable={false}
  value={doc}
  loadOptions={async (search, callback) => {
    const doctors = await fetchDoctors(search);
    const doctorsList = doctors.map(item => ({
      ...item,
      label: item.doctorName,
      value: item.doctorName,
    }));
    callback(doctorsList);
  }}
  backspaceRemovesValue
  placeholder="Search for a doctor..."
  onChange={async (newVal) => {
    updateDoctor(newVal); //has the label and value present due to loadOptions
    const updatedOrder = { ...order };
    updatedOrder.doctorId = newVal.id;
    if (newVal.organization) {
      updatedOrder.organization = newVal.organization;
    } else {
      updatedOrder.organization = '';
    }
    updateOrderRemote(updatedOrder, newVal);
  }}
/>