在反应中将下拉列表的选定值传递给 API

Passing selected value of Dropdown into API in react

您好,当页面加载时,我需要在 dropdown 中填充列表,所以我将相同的列表放在 componentDidMount().

 componentDidMount() {
    axios.get(`http://localhost:8080/country_code`).then((res) => {
      const countryData = res.data;
      this.setState({ countryData });
    });
  }

此数据需要成为下拉列表的一部分。

      <select id="dropdown">
        {this.state.countryData.map((countryData) => (
          <option key={countryData} value={countryData}>
            {countryData}
          </option>
        ))}
      </select>

列表显示如下。

我的要求是,如果用户 select dropdown list 中的任何值 value 应该在 API 中作为参数传递给 backend

我需要在 SelectOption 中做哪些更改。我知道如何使用 axiosreactjs 中编写调用 API。我会管理的。 我的更新代码如下。

<select id="dropdown" onChange={this.downLoadFile(e)}>
                {this.state.countryData.map((countryData) => (
                  <option key={countryData} value={countryData}>
                    {countryData}
                  </option>
                ))}
</select>



downLoadFile(e) {
    this.setState({ selectValue: e.target.value });
    alert(selectValue);
  }


this.state = {
      countryData: [],
      selectValue: '',
    };
    this.handleChange = this.handleChange.bind(this);
    this.downLoadFile = this.downLoadFile.bind(this);
  }

它不工作。我做错了什么?

编辑1:-

 downLoadFile(e) {
    e.preventDefault();
    this.setState({ selectValue: e.target.value });
    alert(selectValue);
  }

   <select id="dropdown" onChange={this.downLoadFile}>
                {this.state.countryData.map((countryData) => (
                  <option key={countryData} value={countryData}>
                    {countryData}
                  </option>
                ))}
              </select>

它给出了以下错误。

constrtor 我有下面的代码。

this.state = {
      selectValue: ''
    };

您应该将函数传递给 onChange 事件。 喜欢:

<select id="dropdown" onChange={(e) => {this.downLoadFile(e)}}>

<select id="dropdown" onChange={this.downLoadFile}>

你的做法就是传递 this.downLoadFile

的 return 值

更新:

alert(selectValue)

必须

alert(this.state.selectValue);

您应该在更新所选状态后获取 API。

downLoadFile(e) {
    this.setState({ selectValue: e.target.value }, () => {
      fetchSomeApi(this.state.selectValue).then((res) => {
         updateSomewhere(res);
      }).catch((error) => console.error(error));
    });
    alert(this.state.selectValue); // < --- changes this line
}

this.setState 有第二个参数作为回调。所以你可以将它用于状态更新事件之后。

此外,您可以更新函数调用。

onChange={this.downloadFile)