英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论