功能组件中的 react-hook-form react-select 发出警告

react-hook-form react-select in functional component gives warning

我正在使用 react-select 5.2.2、reack-hook-form 7.19.5 和 react 17.0.2

我的组件中一切正常,除了当我在 react-select 下拉列表中输入 select 值时,它会在控制台中抛出以下警告:

组件正在将受控输入更改为不受控。这可能是由于值从已定义变为未定义而导致的,这不应该发生。在组件的生命周期内决定使用受控或非受控输入元素。

这是我的组件代码

const [selectedOption, setSelectedOption] = useState(undefined);
const { data: userAreas } = useQuery(GET_AREAS);

const areasList = userAreas && userAreas.getAreasList.map((obj) => {
    const rObj = {};
    rObj.areaValue = obj;
    rObj.label = obj;
    return rObj;
  });

<Label>Area</Label>
          <Controller
            name="area"
            control={control}
            rules={{ required: 'Area is required' }}
            render={({ field }) => (
              <ReactSelect
                isClearable
                {...field}
                placeholder="Select Your Area"
                value={selectedOption}
                onChange={setSelectedOption}
                options={areasList}
              />
            )}
          />

{areasList} 来自 graphql useQuery,因此最初它是未定义的,直到它在后续渲染中接收到数据

我进一步修改了代码以排除未定义但仍然出现警告。这是修改后的代码

const { data: userAreas } = useQuery(GET_AREAS);

const areasList = userAreas?.getAreasList.map((obj) => {
    const rObj = {};
    rObj.areaValue = obj;
    rObj.label = obj;
    return rObj;
  }) || [];

<Label>Area</Label>
          <Controller
            name="area"
            control={control}
            rules={{ required: 'Area is required' }}
            render={({ field }) => (
              <ReactSelect
                isClearable
                {...field}
                placeholder="Select Your Area"
                options={areasList}
              />
            )}
          />

您正在将不可控组件更改为可控组件

检查这个documentation

该值在第一次渲染时未定义,因此无法控制,然后更改该值并且您的组件变得可控

值属性应该是这样的

selectedOption ?? <empty data here>

正在替换

<Controller
    name="area"
    control={control}
    rules={{ required: 'Area is required' }}
    render={({ field }) => (
        <ReactSelect
           isClearable
           {...field}
           placeholder="Select Your Area"
           options={areasList}
        />
    )}
/>

<Controller
            name="area"
            control={control}
            rules={{ required: 'Area is required' }}
            render={({ field }) => (
              <ReactSelect
                isClearable
                value={field.value}
                onChange={field.onChange}
                ref={field.ref}
                placeholder="Select Your Area"
                options={areasList}
              />
            )}
          />

解决了我的问题。