簡體   English   中英

在反應中將下拉列表的選定值傳遞給 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);
  }

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

您應該將 function 傳遞給 onChange 事件。 喜歡:

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

或者

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

你這樣做的方式只是傳遞 this.downLoadFile 的返回值

您應該在更新選定的 state 后獲取 API。

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

this.setState有第二個參數作為回調。 所以你可以在 state 更新事件之后使用它。

此外,您可以更新 function 調用。

onChange={this.downloadFile)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM