一个下拉菜单覆盖另一个下拉菜单的值
我正在使用 javascript React 和 Formik 制作一个页面,并且在一种表单中有两个下拉菜单,我让它们工作,但现在我正在使用它们,当我选择一个值时,另一个值会重置。不知道如何更好地表达,所以我将添加发生的情况的 gif:
这些是我的下拉菜单(两者相同,只是从不同的对象获取值)。
<Field
as="select"
className="custom-select d-block w-100"
name="fk_room"
required
>
<option></option>
{this.state.doctors.map((doctors) => (
<option value={doctors.surname} selected>
{" "}
{doctors.surname}
</option>
))}
</Field>
我偷偷怀疑这可能与我设置状态两次有关
componentDidMount() {
userService.getAllRooms().then((result) => {
this.setState({
rooms: result.map(({ name }) => name),
});
});
userService.getAllEmployees().then((result) => {
this.setState({
doctors: result.map(o => ({name: o.name, surname: o.surname, specialization: o.specialization})),
});
});
}
,即使使用 console.log 看起来我正确地获取了值,我认为由于每次下拉单击都会再次调用 componentDidMount (我认为),所以发生了一些奇怪的事情。 有人处理过类似的问题吗?这是否与我设置状态两次有关,或者我需要以某种方式保存下拉列表中的值? (只有 1 个下拉菜单,我在其中调用过一次状态,效果很好)。 抱歉,如果这完全是新手领域,我对 javascript 和反应非常缺乏经验。 PS 下拉菜单是完全独立的,我在网上找到的所有指南都是关于依赖下拉菜单的,但这不是我想要的最终结果,它们都不应该从填充对象的初始调用中改变。
I'm making a page with javascript react and formik and I have two dropdowns in one form, I got them to work but now that I'm using both of them, when I choose a value with one the other's value resets. Don't know how to word this better so I'll add a gif of what happens:
These are my drop down menus (both identical just taking values from a different object).
<Field
as="select"
className="custom-select d-block w-100"
name="fk_room"
required
>
<option></option>
{this.state.doctors.map((doctors) => (
<option value={doctors.surname} selected>
{" "}
{doctors.surname}
</option>
))}
</Field>
I have a sneaking suspicion it's likely to do with me setting the state twice
componentDidMount() {
userService.getAllRooms().then((result) => {
this.setState({
rooms: result.map(({ name }) => name),
});
});
userService.getAllEmployees().then((result) => {
this.setState({
doctors: result.map(o => ({name: o.name, surname: o.surname, specialization: o.specialization})),
});
});
}
even though with console.log it looks like I get the values correctly, I assume something funky is going on since every dropdown click calls the componentDidMount again (I think).
Has anyone dealt with a similar issue? Does it have to do with me setting the state twice or I need to somehow save the value from the dropdowns? (It worked fine with just 1 dropdown menu where I called the state once).
Sorry if this is complete novice territory I am very inexperienced in javascript and react.
P.S. the dropdowns are completely independent, all the guides I found online were about dependent dropdown menus but this is not the final result I want, they both should never change from the initial call to fill the objects.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)