代码之家  ›  专栏  ›  技术社区  ›  Bear Bile Farming is Torture

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

  •  1
  • Bear Bile Farming is Torture  · 技术社区  · 4 年前
            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 />
              )}
            />
    

    警告信息:

    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`.
    

    自动完成修改 useState ,但 使用状态 AutoComplete .

    这不对吗?

    1 回复  |  直到 4 年前
        1
  •  1
  •   Saeed Shamloo    4 年前

    这是因为你的国家价值观 undefined

    const [country, set_country] = React.useState('');
    

    const [country, set_country] = React.useState(null);
    

    当你不提供 value AutoComplete 归因于 ,MaterialUI认为 作为非受控组件,这意味着MaterialUI认为您自己没有提供任何状态来更新 价值 属于 ,但如果你提供 价值 在…上 自动完成 作为受控组件,这意味着materialUI知道您已经定义了一些状态值来控制 自动完成 .

    在您的示例中,在第一次渲染中 country 所以MaterialUI认为 作为非受控组件,并尝试控制 自动完成 但在接下来的几天里,你的国家不是 未定义 ,因此材料必须改变一些内部决定,这会导致其发出警告。