REACT - 下拉值不动态更新
REACT - Dropdown values not updating dynamically
我是 React 的新手,所以这个问题可能有点愚蠢。我正在尝试从后端获取下拉值。
我面临的问题是即使在异步等待函数 returns 项目之后,程序也没有用项目填充列表。任何帮助将不胜感激。
从后端加载数据的代码:-
getDataSources = async () => {
try {
return await axios.post("http://localhost:5000/configure_get_sources",
{
headers: {
"content-type": "application/json"
}
}
);
}
catch (e) {
console.log(e);
}
};
对于下拉菜单,我有下面提到的代码:-
var selectSources = [];
this.getDataSources().then((res) => {
for (var i = 0; i < res.data.length; i++) {
selectSources.push("<option value='" + res.data[i] + "'>" + res.data[i] + "</option>");
};
});
return (
<div className="container">
<div className="row">
<label className="col-md-4" >Data Source: </label>
<select className="col-md-7">
{
selectSources.map(id =>
<option key={id} value={id}>{id}</option>
)
}
</select>
</div>
</div
);
您需要将选项保存在状态中,以便在检索选项时重新呈现组件。此外,您应该获取 componentDidMount
生命周期方法中的选项。尝试这样的事情:
添加状态
this.state = {
options: []
}
使用componentDidMount
componentDidMount() {
axios.post("http://localhost:5000/configure_get_sources",
{
headers: {
"content-type": "application/json"
}
}
).then(res => {
this.setState({options: res.data});
});
}
这是假设 res.data 作为数组返回,而不是包含数组的对象。
渲染方法
let renderedOptions = this.state.options.map((item, i) => {
return (
<option value={item} key={i}>{item}</option>
)
});
return (
<div className="container">
<div className="row">
<label className="col-md-4" >Data Source: </label>
<select className="col-md-7">
{ renderedOptions }
</select>
</div>
</div
);
我是 React 的新手,所以这个问题可能有点愚蠢。我正在尝试从后端获取下拉值。 我面临的问题是即使在异步等待函数 returns 项目之后,程序也没有用项目填充列表。任何帮助将不胜感激。
从后端加载数据的代码:-
getDataSources = async () => { try { return await axios.post("http://localhost:5000/configure_get_sources", { headers: { "content-type": "application/json" } } ); } catch (e) { console.log(e); } };
对于下拉菜单,我有下面提到的代码:-
var selectSources = []; this.getDataSources().then((res) => { for (var i = 0; i < res.data.length; i++) { selectSources.push("<option value='" + res.data[i] + "'>" + res.data[i] + "</option>"); }; }); return ( <div className="container"> <div className="row"> <label className="col-md-4" >Data Source: </label> <select className="col-md-7"> { selectSources.map(id => <option key={id} value={id}>{id}</option> ) } </select> </div> </div );
您需要将选项保存在状态中,以便在检索选项时重新呈现组件。此外,您应该获取 componentDidMount
生命周期方法中的选项。尝试这样的事情:
添加状态
this.state = {
options: []
}
使用componentDidMount
componentDidMount() {
axios.post("http://localhost:5000/configure_get_sources",
{
headers: {
"content-type": "application/json"
}
}
).then(res => {
this.setState({options: res.data});
});
}
这是假设 res.data 作为数组返回,而不是包含数组的对象。
渲染方法
let renderedOptions = this.state.options.map((item, i) => {
return (
<option value={item} key={i}>{item}</option>
)
});
return (
<div className="container">
<div className="row">
<label className="col-md-4" >Data Source: </label>
<select className="col-md-7">
{ renderedOptions }
</select>
</div>
</div
);