首页 > 解决方案 > 反应 - 下拉值不动态更新

问题描述

我是 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
      );

标签: javascriptreactjsasync-awaitaxiosdropdown

解决方案


您需要将选项保存在状态中,以便在检索选项时重新渲染组件。此外,您应该抓住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
  );

推荐阅读