关于这种级联的下拉列表值请求,通常会有一个异步的问题,可以这样:直接用state的数据push进去,再调用setState(val => […val])保存一下自己的值,这样就可以了。
1、这种方法是错误的,因为map/forEach中async和await不会生效
/** 得到下拉列表值 */
const getDictList = async () => {
service.getAAAAA().then((res: any) => {
if (res && res.length) {
let arr: any = [];
res.map(async (item: any) => {
const val = item.value.toUpperCase();
await getDict(`TYPE_${val}`, false).then(
(result: any) => {
// ---------------------------------
state.push(...result);
setState((val: any) => [...val]);
},
);
});
}
});
};
2、可以用for循环,Promise.all,for of循环,在这些循环里面,才会等待完成async和await的执行,才能得到每次请求到的数据
1、使用for of循环
/** 得到下拉列表值 */
const getDictList = async () => {
service.getAAAAAA().then(async (res: any) => {
if (res && res.length) {
for (const item of res) {
const val = item.value.toUpperCase();
const result = await getDict(`TYPE_${val}`, false);
state.push(...result);
}
setState((val: any) => [...val]);
}
});
};
2、使用for循环
/** 得到下拉列表值 */
const getDictList = async () => {
service.getAAAA().then(async (res: any) => {
if (res && res.length) {
let arr: any = [];
for (let i = 0; i < res.length; i++) {
const val = res[i].value.toUpperCase();
const result = await getDict(`TYPE_${val}`, false);
arr.push(...result);
}
setState(arr);
}
});
};
3、使用Promise.all方法
const getDictList = async () => {
service.getAAAAAA().then((res: any) => {
if (res && res.length) {
let promises: Promise<any>[] = [];
res.forEach((item: any) => {
const val = item.value.toUpperCase();
const promise = getDict(`TYPE_${val}`, false);
promises.push(promise);
});
Promise.all(promises).then((results) => {
results.forEach((result: any) => {
state.push(...result);
});
setState([...allExpressProTypeList]);
});
}
});
};