MUI 自动完成默认值未显示?

发布于 2025-01-15 17:05:59 字数 1092 浏览 2 评论 0原文

import * as React from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

export default function ComboBox() {
  const [top100Films, settop100Films] = React.useState([]);
  const value = 1;
  React.useEffect(() => {
    fetch("https://reqres.in/api/users?page=1")
      .then((res) => res.json())
      .then(({ data }) => {
        console.log(data);
        settop100Films(data);
      })
      .catch((err) => console.log(err));
  }, []);
  // if (!top100Films.length > 0) {
  //   return "";
  // }
  return (
    <Autocomplete
      disablePortal
      id="combo-box-demo"
      defaultValue={
        top100Films.find((ele) => ele.id === value) || null
      }
      options={top100Films}
      getOptionLabel={(data) => data.first_name}
      sx={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label="Movie" />}
    />
  );
}

如果我取消注释此 if 条件,它就可以正常工作。但我不想要这种行为。最初 defalutValue 将为 null。获取数据后,默认值将更改为精确值。但该值未显示在自动完成中。

import * as React from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

export default function ComboBox() {
  const [top100Films, settop100Films] = React.useState([]);
  const value = 1;
  React.useEffect(() => {
    fetch("https://reqres.in/api/users?page=1")
      .then((res) => res.json())
      .then(({ data }) => {
        console.log(data);
        settop100Films(data);
      })
      .catch((err) => console.log(err));
  }, []);
  // if (!top100Films.length > 0) {
  //   return "";
  // }
  return (
    <Autocomplete
      disablePortal
      id="combo-box-demo"
      defaultValue={
        top100Films.find((ele) => ele.id === value) || null
      }
      options={top100Films}
      getOptionLabel={(data) => data.first_name}
      sx={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label="Movie" />}
    />
  );
}

If i uncomment this if condition it works fine. But i don't want that behaviour. Initially defalutValue will be null. After fetching data default value will be changed to the exact value. But the value not shown in autocomplete.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

金兰素衣 2025-01-22 17:05:59

在defaultValue中你不应该使用console.log,你可以尝试这样:

value ={top100Films}

In the defaultValue you should not use console.log, you can try like this:

value ={top100Films}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文