首页 > 解决方案 > 从 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 不能为空,但选择菜单中的每个选项都有一个值。我是新手,但也许该值仅在更改时才实际分配?

标签: reactjsjoi

解决方案


您需要编辑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 });
}

推荐阅读