选择表单字段时不填充ReactJS状态中的选项

问题描述 投票:0回答:2

这是我的选择功能

import React from "react";

const Select = ({ name, label, options, error, ...rest }) => {
  return (
    <div className="form-group">
      <label htmlFor={name}>{label}</label>
      <select {...rest} id={name} name={name} className="form-control">
        <option value="" />
        {options.map((option) => (
          <option key={option.id} value={option.id}>
            {option.name}
          </option>
        ))}
      </select>
      {error && <div className="alert alert-danger">{error}</div>}
    </div>
  );
};

export default Select;

这是组件状态

state = {
    data: {
      vat: "",
      city: "",
      country: "",
      mobile_number: "",
      address: "",
      has_conference: false,
      star_rating: "",
    },
    errors: {},
    hotel_type: [],
  };

此功能用于填充hotel_type中的数据

populateHotel_Types = () => {
    let hotel_type = [...this.state.hotel_type];
    hotel_type = [
      { id: "hotel", value: "hotel", name: "Hotel" },
      { id: "apartment", value: "apartment", name: "Apartment" },
      { id: "villa", value: "villa", name: "Villa" },
    ];
    this.setState({ hotel_type });
  };

最后是渲染功能

           {this.renderSelect(
              "hotel_type",
              "Hotel Type",
              this.state.hotel_type
            )}

渲染选择功能

renderSelect(name, label, options) {
    const { data, errors } = this.state;
    return (
      <Select
        options={options}
        name={name}
        value={data[name]}
        label={label}
        onChange={this.handleChange}
        error={errors[name]}
      />
    );
  }

现在我正在努力获取在renderselect函数中填充的数据。我反应很新,我实际上以为这可能是一个愚蠢的问题,因此请耐心等待。此代码可能有什么问题。请帮忙。谢谢

reactjs components
2个回答
0
投票

我认为首先,您在这里遇到问题:

populateHotel_Types = () => {
    let hotel_type = [...this.state.hotel_type];
    hotel_type = [
      { id: "hotel", value: "hotel", name: "Hotel" },
      { id: "apartment", value: "apartment", name: "Apartment" },
      { id: "villa", value: "villa", name: "Villa" },
    ];
    this.setState({ hotel_type });
  };

[这里,您是用州名填写hotel_type。在下面,您正在重新定义数组,因此您将只有这3个新对象。所以应该这样做以获得完整列表:

 populateHotel_Types = () => {
    const hotel_type = [
       ...this.state.hotel_type,
      { id: "hotel", value: "hotel", name: "Hotel" },
      { id: "apartment", value: "apartment", name: "Apartment" },
      { id: "villa", value: "villa", name: "Villa" },
    ];
    this.setState({ hotel_type });
  };

0
投票

我怀疑这是一个愚蠢的问题,的确是。我忘记了在populateHotel_Types函数中运行函数componentDidMount。因此,状态未得到适当更新。我将其留在这里,以便像我这样的新手都能得到这种情况的答案

© www.soinside.com 2019 - 2024. All rights reserved.