【发布时间】: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