[React][MUI] 警告:渲染不同组件时无法更新组件

问题描述 投票:0回答:1

我正在使用 AutoComplete(MUI) 创建国家/地区选择器,但收到以下错误消息。

Warning: Cannot update a component (`CountrySelectorPopup`) while rendering a different component (`ForwardRef(Autocomplete)`). To locate the bad setState() call inside `ForwardRef(Autocomplete)`

仅当我在函数内部有 setState

setState(filtered[filtered.length - 1])
时,才会发生此错误。

const handleFilterOptions = useCallback((
    options: TermObject[],
    params: FilterOptionsState<TermObject>
  ) => {
    const filtered = filter(options, params);
    setState(filtered[filtered.length - 1]);
    return filtered;
  }, [1]);

我将此函数传递给 AutoComplete filterOptions。

<Autocomplete
  clearOnBlur
  fullWidth
  freeSolo
  onChange={(_e, _newValue) => setValue("")}
  onInputChange={(_e, newValue) => setInputValue(newValue)}
  value={value}
  inputValue={inputValue}
  open={true}
  filterOptions={handleFilterOptions}...

我相信这是与 AutoComplete 相关的错误,但谁能告诉我为什么会发生这种情况,因为对我来说这似乎不是一个糟糕的 setState 调用。

material-ui
1个回答
0
投票

您需要从

setState
移出
handleFilterOptions
功能。 将
setState
传递到
onInputChange
道具内。

这一切都是因为渲染行为

Autocomplete
组件。

© www.soinside.com 2019 - 2024. All rights reserved.