【问题标题】:Getting results of a MongoDB query to use in a select menu获取 MongoDB 查询的结果以在选择菜单中使用
【发布时间】:2021-11-14 07:26:42
【问题描述】:

我正在开发一个允许您根据位置在数据库中搜索人员的网站。最初,下拉菜单(选择)填充了可用人员所在的省份。我正在尝试使用 mongo 查询来填充该选择菜单。但是当我尝试获取函数之外的值时,它不起作用并且选择菜单变为空。

import * as React from "react";
import axios from "axios";
  
const Locations = () => {

  let options = null;

  function axiosTest() {
    // This is a server link i created that runs a query that returns distinct provinces from the database
    const promise = axios.get("/api/v2/people/provinces");
    const dataPromise = promise.then(result => result.data).then(data => {console.log(data);return data;});
    // The console.log() above displays all the objects that are in the query given by the server link in an array
    // e.g. ['British Columbia', 'Alberta', 'Saskatchewan', etc.]
  }
  
  var type = axiosTest();
  console.log(type);  // now it displays it as "undefined"

  if (type) {
    options = type.map((el) => <option key={el}>{el}</option>);
  }

  return (
    <div
      style={{
        padding: "16px",
        margin: "16px",
      }}
    >
      <form>
        <div>
          <select>
            {
              /** This is where we have used our options variable */
              options
              // and the select menu is shown as blank, because it doesn't have any options to fill it with
            }
          </select>
        </div>
      </form>
    </div>
  );
};
  
export default Locations;

有人可以帮我解决这个问题吗?它与线程和并发有关吗?不幸的是,我对此感到生疏。

【问题讨论】:

    标签: javascript reactjs mongodb drop-down-menu


    【解决方案1】:

    函数axiosTest() 不返回任何内容。您应该指定更改代码,以便函数返回数据库查询的结果。您还可以使用async/await 更改.then() 语法,这样您的代码将变得更具可读性。

    const Locations = async () => {
    
      let options = null;
    
      function axiosTest() {
        return axios.get("/api/v2/people/provinces");
      }
      
      var type = await axiosTest();
      console.log(type); 
    
      ...
    
    };
    

    【讨论】:

    • 当我尝试将“async”添加到 const Locations 行时,它给了我这个:错误:对象作为 React 子项无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组。我该如何解决这个问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    相关资源
    最近更新 更多