reactjs - ReactJS:使用 AXIOS 进行 API 调用并在选择中使用
问题描述
我正在尝试进行 api 调用并在选择中使用它,但我的选择是空的
const [intergrationLevel, setIntegrationLevel] = useState<any>(null);
useEffect(() => {
async function fectIntegrationLevel() {
let response = await fetch('.../api/integrations');
response = await response.json();
setIntegrationLevel(response);
}
fectIntegrationLevel();
if (isNew) {
props.reset();
} else {
props.getEntity(props.match.params.id);
}
}, []);
console.log('intergrationLevel', intergrationLevel);
return (
//...
<div className="col-md-4">
<AvGroup>
<Label>Level</Label>
<AvInput
id="integration-level"
data-cy="integration-level"
type="select"
className="form-control"
name="realm"
/>
{intergrationLevel
? intergrationLevel.map(int => (
<option value={int.cod} key={int.cod}>
{int.cod}
</option>
))
: null}
</AvGroup>
我的 console.log(integrationLevel) 开头为 null (这应该是问题所在),然后它被填充,但选择 no。我能怎么做?
编辑解释:
我会进行 api 调用来检索数据列表,并使用表单中选择中的数据来发出请求..
我试图进行这个 api 调用,并且我已经使用了 setIntegrationLevel(response);
在 intergrationLevel 中保存列表,但是当我在我的选择上使用 intergrationLevel 时,这个 intergrationLevel 是空的(可能是因为当返回开始时 api 调用没有结束)
EDIT2:(用选择包装)
编辑3:
现在的情况是:
解决方案
您没有在完成网络调用时渲染您的组件。这就是为什么我在依赖数组中添加值
const [intergrationLevel, setIntegrationLevel] = useState<any>(null);
async function fectIntegrationLevel() {
let response = await fetch('.../api/integrations');
response = await response.json();
setIntegrationLevel(response);
}
useEffect(() => {
if (!intergrationLevel){
fectIntegrationLevel();
}
if (isNew) {
props.reset();
} else {
props.getEntity(props.match.params.id);
}
}, [intergrationLevel]);
console.log('intergrationLevel', intergrationLevel);
return (
//...
<div className="col-md-4">
<AvGroup>
<Label>Level</Label>
<AvInput
id="integration-level"
data-cy="integration-level"
type="select"
className="form-control"
name="realm"
/>
{intergrationLevel
? intergrationLevel.map(int => (
<option value={int.cod} key={int.cod}>
{int.cod}
</option>
))
: null}
</AvGroup>
推荐阅读
- python - Pandas 合并具有相同 id 行的列表
- angular - 以角度的静态方法访问 ag-Grid ColumnApi
- mysql - 在 Mysql for Postgresql 中替代“set @myvariable = value”
- intellij-idea - 如何在 IntelliJ IDEA 的拆分选项卡中打开新文件?
- mysql - MySQL CREATE TABLE FROM VIEW 与 PRIMARY KEY
- python - 如何从 Python 中的字符串中提取数字并返回一个列表?
- software-design - 在洋葱、六边形或干净架构中,域模型是否可以包含与数据库中的域模型不同的属性?
- ios - 我想在我的通知中显示图像,我试图在扩展通知服务中这样做,但它没有用
- javascript - for-loop 中的 Discord.js setTimeout 正在同时打印值,有没有办法让这个简单的程序工作
- javascript - Angular 8:如何从 json REST API 创建枚举