javascript - Material UI 自动完成无法将选项参数识别为数组

标签 javascript reactjs typescript autocomplete material-ui

我正在尝试创建一个自动完成字段,该字段从组件状态(状态从后端获取)中获取选项。这是我的组件:

export const Person: React.FC<PersonProps> = ({name, avatar, setMainState}: PersonProps) => {
  const [location, setLocation] = useState('');
  const [options, setOptions] = useState([]);
  const change = (event: any) => {
    setLocation(event.target.value)
    setMainState(event.target.value)
  }
  
  useEffect(() => {
    axios
      .get(`http://localhost:8080/autocomplete/?str=` + location)
      .then(res => {
        setOptions(res.data);
      })
  },[location])

  return <Box display="flex" height="30%">
    <Typography>{name}</Typography>
    <Autocomplete
      id="combo-box-demo"
      options={options}
      getOptionLabel={(option) => option as string}
      style={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label="Combo box" variant="outlined" />}
    />
  </Box>
};

但出于某种原因,我的状态中的选项数组未被识别为数组(尽管我使用空数组对其进行了初始化)。我收到此警告:

index.js:1 Warning: Failed prop type: Invalid prop `options` of type `object` supplied to `ForwardRef(Autocomplete)`, expected `array`.
    in ForwardRef(Autocomplete) (created by WithStyles(ForwardRef(Autocomplete)))
    in WithStyles(ForwardRef(Autocomplete)) (at Person.tsx:56)
    in div (created by Styled(MuiBox))
    in Styled(MuiBox) (at Person.tsx:49)
    in Person (at Main.tsx:14)
    in div (created by Styled(MuiBox))
    in Styled(MuiBox) (at Main.tsx:13)
    in div (created by Styled(MuiBox))
    in Styled(MuiBox) (at Main.tsx:12)
    in Main (at App.tsx:11)
    in div (at App.tsx:10)
    in App (at src/index.tsx:6)

您知道可能是什么原因吗?任何想法都会有所帮助:) 谢谢!

最佳答案

我的假设是,当您这样做时: setOptions(res.data); 您正在将 options 设置为一个对象,而不是一个数组。

事实上,错误是这样说的: ...提供给“ForwardRef(自动完成)”的“对象”类型的“选项”,预期为“数组”。 所以它需要一个数组,但你提供的是一个对象

关于javascript - Material UI 自动完成无法将选项参数识别为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63800165/

相关文章:

javascript - 可编辑元素占位符不平滑

javascript - Bootstrap : Better way of lining up elements in columns and rows when you have to skip some

javascript - 以这种方式使用对象属性是否可以接受?

typescript - 编译器无法识别自定义 TS 类型

javascript - 配置 Express 和 Angular

javascript - 使用 NW.js (Node Webkit) 执行 Windows 文件/事件

reactjs - Redux 状态不会随着操作分派(dispatch)而更新

angular2 map 数据作为特定对象类型

javascript - Ionic 2-无限滚动不在第二个滚动上调用方法

javascript - 使用AJAX时何时使用POST方法解释