MUI Autocomplete 不接受 Value

huangapple go评论78阅读模式
英文:

MUI Autocomplete doesnt take Value

问题

我有一个包含所有用户的自动完成功能。当用户在不同的网站上点击按钮时,会被重定向到此网站,并通过fetch获取用户的ID。现在我想要自动选择具有相应ID的用户。但是当我尝试时,没有选择任何内容。

示例:https://codesandbox.io/s/frosty-water-tv27nn?file=/src/App.tsx

英文:

I have an Autocomplete with all user in it.
When a user clicks on a Button on a different site it gets redirected to this site and i get the id of the user with a fetch.
Now i want that the User with the Corresponding ID is automaticly selected.
But when i try it nothing gets selected.

Example: https://codesandbox.io/s/frosty-water-tv27nn?file=/src/App.tsx

答案1

得分: 1

有控制台警告提醒:

> MUI: 一个组件正在改变 Autocomplete 的无控制值状态为受控制的状态。

这意味着你的值从 undefined 改变为其他值。这会阻止它正常工作。你的初始值应该是 null,而不是 undefined

const [selectedUser, setSelectedUser] = useState(null);

然后它将按预期工作

另外,不要直接在组件主体中直接更新状态,这会在每次渲染时对状态进行推送

userArray.push({ id: "s", fullName: "d" });  // 永远不要直接更新状态!
英文:

There is a warning in the console telling

> MUI: A component is changing the uncontrolled value state of Autocomplete to be controlled.

That means your value changes from undefined to something else. And that prevents it from working correctly. Your initial value should be null, not undefined

  const [selectedUser, setSelectedUser] = useState(null);

Then it will work as expected

And also don't update the state directly in the body of the component, it will push to that state on each render

userArray.push({ id: "s", fullName: "d" });  // never update state directly!

huangapple
  • 本文由 发表于 2023年7月6日 22:25:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76629863.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定