javascript - 反应 - 下拉值不动态更新
问题描述
我是 React 新手,所以这个问题可能有点愚蠢。我正在尝试从后端获取下拉值。我面临的问题是,即使在 async-await 函数返回项目之后,程序也没有用项目填充列表。任何帮助,将不胜感激。
从后端加载数据的代码:-
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
);
推荐阅读
- java - IntelliJ IDEA 社区 + Java 11
- c# - 通过套接字发送 UDP 广播会不断引发异常
- android - 尺寸大小 = driver.manage().window().getSize() 在 android 设备上不起作用
- java - 如何处理未使用的@Override 方法?
- javascript - threejs 线跟随几何
- tcl - 访问在不同命名空间中打开的文件处理程序
- proxy - CNTLM 代理和 .pac 文件
- dask - 如何使用 dask 将 SVC 分发给不同的工作人员(在其他计算机上)
- python - 在 Pytorch 中计算欧几里得范数.. 难以理解实现
- java - 在 Windows 中创建的 tar.gz 在 linux 下无法正确解包 - ArchiverFactory / org.rauschig.jarchivelib.Archiver