MUI文本字段中API的默认值
我有一种使用材料UI构建的表格,我希望从API中获得其默认值。主要想法是一个编辑屏幕,用户可以在其中编辑详细信息,然后将它们发送回。但是,我似乎根本无法正常工作。 首先,我使用axios.get请求获取数据:
let { id } = useParams();
const [unit, setUnit] = useState("");
useEffect(() => {
axios.get(`http://localhost:3001/units/${id}`).then((response) => {
setUnit(response.data);
});
}, []);
然后,我将我想要的值分配给状态:
const [name, setName] = useState(unit.name);
最后,我尝试将其设置为值(因为我读到无法控制DefaultValue):
<TextField
required
label="Unit Name"
value={name}
onChange={(event) => {setName(event.target.value)}}
fullWidth
variant="outlined"
/>
但是,该字段确实确实不包含任何值。我尝试将单位分配给正常const并将其分配给TextField值,但它起作用,但我无法对其进行编辑。
I have a form that I built using material UI that I would like to have their default values from an API. The main idea is an Edit screen where the user can edit the details and then send them back. However, I cannot seem to get it working at all.
First, I get the data using an axios.get request:
let { id } = useParams();
const [unit, setUnit] = useState("");
useEffect(() => {
axios.get(`http://localhost:3001/units/${id}`).then((response) => {
setUnit(response.data);
});
}, []);
Then I assign the value I want to a state:
const [name, setName] = useState(unit.name);
Finally, I try to set it as the value (since I read that defaultValue cannot be controlled):
<TextField
required
label="Unit Name"
value={name}
onChange={(event) => {setName(event.target.value)}}
fullWidth
variant="outlined"
/>
However, the field does not contain any value. I tried assigning unit.name to a normal const and assign it to the textfield value and it worked but I could not edit it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的情况下,您可以将值更改为默认值,然后可以对其进行编辑。
In your case, you could change the value to the default value and then you could edit it.
工作解决方案是在接收到数据的Axios请求后设置名称:
然后将其设置为值并正常使用Onchange
Working solution is setting the name after receiving the Axios request with the data:
Then set it as the value and using the onChange normally
我遇到了一个类似的问题,我首先将数据获取在主组件上,并将整个值传递给编辑模式,只要有一个值,它都可以正常工作,但是如果任何值是null的,它将本质上是用于编辑的崩溃
,我只是在模态组件中有一个新的形式状态,然后更改将其传递给表单状态。
I am running into a similar issue, I am first getting the data on the main component and the passing the entire value to the edit modal, it works fine as long as there is a value, but if any of the value's are null it will essentially crash
for Editing, I just have a new form state in the modal component, and on Change pass that to the form state.