嗨,我需要在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>
串列顯示如下。

我的要求是,如果用戶選擇dropdown list了value應該API作為引數傳入的任何值backend。
我需要在Selector中進行哪些更改Option。我知道如何reactjs使用axios.that 我將管理的方式撰寫呼叫 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: ''
};
uj5u.com熱心網友回復:
您應該在更新所選狀態后獲取 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)
uj5u.com熱心網友回復:
您應該將函式傳遞給 onChange 事件。喜歡:
<select id="dropdown" onChange={(e) => {this.downLoadFile(e)}}>
或者
<select id="dropdown" onChange={this.downLoadFile}>
你這樣做的方式只是傳遞 this.downLoadFile 的回傳值
更新:
alert(selectValue)
必須是
alert(this.state.selectValue);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/414221.html
標籤:
上一篇:DjangoAllauth:重復鍵值違反唯一約束:鍵(用戶名)=()已經存在
下一篇:顫振問題:如何洗掉串列資料的括號
