我正在推送从REST API获取的数据,但未定义。如何以正确的方式获取这些数据?
我来自API的回复:
[{
"id": 1,
"positionName": "Accounting Assistant III"
}, {
"id": 2,
"positionName": "Web Developer III"
}, {
"id": 3,
"positionName": "Graphic Designer"}]
我在React中的代码:
const getPosistions = async () => {
const response = await fetch('http://localhost:8080/api/positions/');
const myJson = await response.json();
return myJson;
}
var positionsChoices;
getPosistions().then(function (result) {
positionsChoices = result;
});
const EmployeeCreate = props => (
<Create {...props}>
<SimpleForm>
<SelectInput
source="id"
choices={positionsChoices}
optionText="positionName"
optionValue="id"
/>
</SimpleForm>
</Create>
);
答案 0 :(得分:2)
prop
,state
或context
的新值,否则当可变变量更改时, React不会重新呈现。对于这种情况,state
似乎最合适-请阅读State and Lifecycle了解更多信息。
作为奖励,如果您想查看React Hooks的作用:
import React, {useState, useEffect} from 'react';
const getPosistions = async () => {
const response = await fetch('http://localhost:8080/api/positions/');
const myJson = await response.json();
return myJson;
}
const EmployeeCreate = props => (
const [positionsChoices, setPositionsChoices] = useState();
useEffect(() => {
getPosistions().then((result) => setPositionsChoices(result));
}, []);
<Create {...props}>
<SimpleForm>
<SelectInput
source="id"
choices={positionsChoices}
optionText="positionName"
optionValue="id"
/>
</SimpleForm>
</Create>
);