reactjs - 从 mongodb 设置选择菜单的默认值
问题描述
我有一个从数据库填充的下拉列表。第一个选项是 'none'(在数据库中使用 objectId 的实际记录),它应该是默认选项,只有在用户愿意时才需要更改,否则在提交表单时应该只使用该初始值。但是,即使它被选中并且具有有效的 objectId,我仍然会收到一个验证错误,指出该字段为空。只有当我从选择菜单中选择其他内容或选择其他内容然后再次选择“无”时,验证错误才会消失。我正在使用Joi 浏览器进行验证。
schema = {
subcategoryId: Joi.string()
.required()
.label("Subcategory"),
}
这是选择菜单:
<Form onSubmit={this.handleSubmit}>
<Form.Group controlId="subcategoryId">
<Form.Label>Sub-category</Form.Label>
<Form.Control
as="select"
name="subcategoryId"
value={this.state.data.subcategoryId}
onChange={this.handleChange}
error={this.state.errors.subcategory}
>
{this.state.subcategories.map(subcategory => (
<option key={subcategory._id} value={subcategory._id}>
{subcategory.name}
</option>
))}
</Form.Control>
{this.state.errors.subcategoryId && (
<Alert variant="danger">
{this.state.errors.subcategoryId}
</Alert>
)}
</Form.Group>
这是我的状态:
state = {
data: {
name: "",
description: "",
categoryId: "",
subcategoryId: "",
price: ""
},
categories: [],
subcategories: [],
errors: {}
};
const { data: subcategories } = await getSubcategories();
this.setState({ subcategories });
这是我希望默认选择的下拉列表第一个字段的 html 输出:
<option value="5d4b42d47b454712f4db7c67">None</option>
我得到的错误是类别 ID 不能为空,但选择菜单中的每个选项都有一个值。我是新手,但也许该值仅在更改时才实际分配?
解决方案
您需要编辑componentDidMount
. 获得子类别后,您需要将状态设置为this.state.data.subcategoryId
类别之一。这是因为您使用的是受控组件。否则,它仍将设置为""
,这不是组件的有效值之一<select>
,并且可能是它未能通过验证的原因。
async componentDidMount() {
// getting a copy of this.state.data so as not to mutate state directly
const data = { ...this.state.data };
const { data: subcategories } = await getSubcategories();
// filter the array to a new array of subcategories that have the name === 'none'
const arrayOfSubcategoriesWhereNameIsNone = subcategories.filter(i => i.name === 'none');
const getIdOfFirstElementOfArray = arrayOfSubcategoriesWhereNameIsNone [0]._id;
//set getIdOfFirstElementOfArray equal to the function's local copy of this.state.data.subcategoryId
data.subcategoryId = getIdOfFirstElementOfArray;
// update the state with the mutated object (the function's local copy of this.state.data)
this.setState({ subcategories, data });
}
推荐阅读
- html - 如何设置嵌套柔性显示的边距/填充?
- android - 更改在 RecyclerView.Adapter 上使用 getItem() 创建的对象的值会导致原始对象的值发生更改
- react-native - 水平滚动视图,一列中有 2 个项目,一次可见 3 个项目
- spring-security - spring-security 示例 saml2login 错误 Metadata not found
- reactjs - 在redux中为多个组件使用`requestAnimationFrame`
- javascript - 在 HTML5 视频中防止键盘上的向后和向前键
- javascript - 使用角度从服务器端 php 文件中获取 json 数据?
- node.js - 无法重新初始化并从我的 catch 语句返回错误响应
- python - 为什么在python中输入带有前导0的数字时会显示错误(不确定这是否与其他语言相同)?
- javascript - Open Weather API 无法在 Safari 或 Firefox 中运行