我正在嘗試使用頁面加載后來自 API 呼叫的值填充我的選擇下拉選項。目前,只有在您觸摸并取消選擇選擇欄位后才會生成選項。在頁面加載時,選項不會被填充并且是空的。我查看了建議使用 React-select 包的其他類似問題,但我正在尋找一種僅通過 react 來完成此操作的方法,但我沒有任何運氣找到解決方案。請告知我如何實作這一目標或在哪里可以獲得幫助。我在下面附上了我的代碼。親切的問候。
import { Form } from "react-bootstrap";
import { Field, ErrorMessage } from "formik";
import axios from "axios";
function CompanySelect(props) {
const [options, setOptions] = useState([]);
useEffect(() => {
const opt = [
{
key: "Select a company",
value: "",
},
];
(async () => {
const { data } = await axios.get("http://localhost:5000/api/company/");
data.forEach((value) => {
opt.push({
key: value.name,
value: value.id,
});
});
})();
setOptions(opt);
}, []);
const { label, name, ...rest } = props;
return (
<Form.Group className="mb-2">
<Form.Label htmlFor={name}>{label}</Form.Label>
<Field id={name} name={name} {...rest} as={Form.Select}>
{options.map((option) => {
return (
<option key={option.value} value={option.value}>
{option.key}
</option>
);
})}
</Field>
<ErrorMessage className="text-danger" name={name} component={Form.Text} />
</Form.Group>
);
}
export default CompanySelect;
uj5u.com熱心網友回復:
您在錯誤的時間更新您的狀態,就在觸發異步之后axios.get但在結果實際出現之前。所以當狀態更新實際發生時,opt 還不包含從 axios 獲取的資料。這是固定版本:
import { Form } from "react-bootstrap";
import { Field, ErrorMessage } from "formik";
import axios from "axios";
function CompanySelect(props) {
const [options, setOptions] = useState([]);
useEffect(() => {
async function fetchData() {
// Fetch data
const { data } = await axios.get("http://localhost:5000/api/company/");
const results = []
// Store results in the results array
data.forEach((value) => {
results.push({
key: value.name,
value: value.id,
});
});
// Update the options state
setOptions([
{key: 'Select a company', value: ''},
...results
])
}
// Trigger the fetch
fetchData();
}, []);
const { label, name, ...rest } = props;
return (
<Form.Group className="mb-2">
<Form.Label htmlFor={name}>{label}</Form.Label>
<Field id={name} name={name} {...rest} as={Form.Select}>
{options.map((option) => {
return (
<option key={option.value} value={option.value}>
{option.key}
</option>
);
})}
</Field>
<ErrorMessage className="text-danger" name={name} component={Form.Text} />
</Form.Group>
);
}
export default CompanySelect;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477776.html
標籤:javascript 反应 异步 异步等待
下一篇:創建異步Task<T>而不運行
