当值设置为它修改的 useState 时,AutoComplete 会发出红色警告

una*_*der 7 html javascript autocomplete reactjs material-ui

        const [country, set_country] = useState();

        <Autocomplete
          autoHighlight={true} //needed
          autoSelect={true}
          id="geo-select-country"
          options={all_country}
          value={country} // culprit that causes red warning
          onChange={(event, selected_country) => {
            set_country(selected_country);
          }}
          classes={autocomplete_classes}
          renderInput={(params) => (
            <TextField {...params} label={"Country"} margin="none" focused />
          )}
        />
Run Code Online (Sandbox Code Playgroud)

警告信息:

index.js:1 MUI: A component is changing the uncontrolled value state of Autocomplete to be controlled.
Elements should not switch from uncontrolled to controlled (or vice versa).
Decide between using a controlled or uncontrolled Autocomplete element for the lifetime of the component.
The nature of the state is determined during the first render. It's considered controlled if the value is not `undefined`.
Run Code Online (Sandbox Code Playgroud)

AutoComplete 修改useState,但 的值useState修改AutoComplete

这不正确吗?

Sae*_*loo 10

这是因为您的国家/地区值位于undefined第一次渲染中,只需为您的国家/地区提供初始值,如下所示:

const [country, set_country] = React.useState('');
Run Code Online (Sandbox Code Playgroud)

或者

const [country, set_country] = React.useState(null);
Run Code Online (Sandbox Code Playgroud)

当你不提供value属性 onAutoComplete或设置value属性时undefined,MaterialUI 会认为AutoComplete是不受控制的组件,这意味着实际上 MaterialUI 认为你没有自己提供任何状态来更新 of valueAutoComplete但是如果你提供了valueon AutoComplete,materialUI 认为AutoComplete是受控组件,这意味着materialUI知道你已经定义了一些状态值来控制 的值AutoComplete

在您的示例中,在第一个渲染中,您的countryis undefined,因此 MaterialUI 认为AutoComplete是不受控制的组件,并尝试自己控制 的值AutoComplete,但在下一个渲染中,您的国家不是undefined,因此材质必须更改一些内部决策,这导致它抛出的警告。