簡體   English   中英

材料 ui 自動完成無法將選項參數識別為數組

[英]material ui autocomplete doesn't recognize options parameter as array

我正在嘗試創建一個自動完成字段,該字段從組件狀態中獲取選項(狀態從后端獲取它)。 這是我的組件:

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設置為對象,而不是數組。

事實上,錯誤說: ..."options" of type "object" supplied to "ForwardRef(Autocomplete)", expected "array". 所以它需要一個數組,但您提供的是一個對象

  <Autocomplete
              id="free-solo-2-demo"
              value={search.scheme_name}
              className={classes.textInput}
              options={[...schemeList]}
              getOptionLabel={(schemeList) => schemeList.scheme_name || ""}
              onChange={(e, value) => {
                if (value !== null) {
                  setSearch({ ...search, scheme_name: value });
                } else {
                  setSearch({ ...search, scheme_name: "" });
                }
              }}
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="Scheme Name"
                  name="scheme_name"
                  // margin="normal"
                  variant="outlined"
                  size="small"
                  InputProps={{
                    ...params.InputProps,
                    type: "search",
                  }}
                />
              )}
            />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM