我是React的新手,我正在制作一个应用程序,我必须在地图函数内调用API,或者我认为。
首先,我调用一个API,它返回一个元素列表,这些元素以剑道的形式呈现,就像这样:
import { Form, Field, FormElement } from "@progress/kendo-react-form";
...
const [tempAtr, setTempAtr] = useState([]);
...
const resAtr = await services.getTemplateSessionAtributi(sesijaV);
setTempAtr(resAtr.data.rlista); //tempAtr is filled with a list of elements (attributes)
...
{tempAtr.map((data) =>
<Field
required={data.required=== 1 ? true : false}
disabled={data.read_only === 1 ? true : false}
name={data.name}
component={
data.tpodatka_id === 1 ?Input:
data.tpodatka_id === 2 ?Input:
data.tpodatka_id === 3 ?DatePicker:
data.tpodatka_id === 4 ?DropDownList:
data.tpodatka_id === 5 ?TextArea :
data.tpodatka_id === 6 ?DropDownList:
data.tpodatka_id === 7 ?DropDownList:
data.tpodatka_id === 8 ?MultiSelect:
data.tpodatka_id === 9 ?MultiSelect:
Input}
label={data.name}
data={
data.tpodatka_id === (4 || 6 || 7 || 8 || 9) ?
**call an API and fetch data to fill the dropdown for that specific attribute id ** :
null
}
textField={data.tpodatka_id === (4 || 6 || 7 || 8 || 9) ? "name" : null}
dataItemKey={data.tpodatka_id === (4 || 6 || 7 || 8 || 9) ? "id" : null}
/>)}
所以在数据部分,我必须调用一个API与attribut_id作为参数,所以我可以获取下拉值的属性,我不知道怎么做?可以有1或5或15个下拉属性,所以我能想到的唯一的事情是调用API内部的map函数和赋值在它的返回。
帮任何人吗?
最佳选择是提取dropdown
- a单独的反应组分&在useEffect
中调用API。你可以通过id
作为道具。示例(Codesandbox)
import React from "react";
import "./styles.css";
function YearDropDown(props) {
const [loading, setLoading] = React.useState(true);
const [items, setItems] = React.useState([]);
const [value, setValue] = React.useState("2013");
const { drilldowns } = props;
React.useEffect(() => {
let unmounted = false;
async function getCharacters() {
const response = await fetch(
`https://datausa.io/api/data?drilldowns=${drilldowns}&measures=Population`
);
const body = await response.json();
if (!unmounted) {
setItems(body.data.map(({ Year }) => ({ label: Year, value: Year })));
setLoading(false);
}
}
getCharacters();
return () => {
unmounted = true;
};
}, [drilldowns]);
return (
<select
disabled={loading}
value={value}
onChange={(e) => setValue(e.currentTarget.value)}
>
{items.map(({ label, value }) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
);
}
export default function App() {
return (
<div className="App">
<YearDropDown drilldowns="Nation" />
</div>
);
}