[英]How to add a deeply nested object to a deeply nested Array in a React Reducer?
[英]How to asynchronously manipulate a deeply nested object by referennce
我正在做一個網格項目,我正在操作一個模式並基於它呈現頁面。 因此,我將架構的引用傳遞給 function,其中 function 將操縱深度嵌套的 object,例如,
{
URL: "some.url"
paramas: {"some params}
}
至
{
URL: "some.url"
params: {"some params}
props:{
data:[] || {}
}
}
這種操作將基於 URL 和參數發生,所以我需要使用 forEach 循環,但不幸的是,forEach 循環不是異步的。
在這里,如果我想從其他模塊操作所有這些對象(超過 100 個)並且它必須是異步的,我不知道我需要做什么。
演示架構:
{
"name": "home",
"path": "/",
"header": "top_header",
"footer": "bottom_footer",
"rows": [
{
"row_class": "bg-white",
"columns_class": "cols-66-33 cols-separated cols--height-equal",
"column_1": [
{
"name": "Coral/HomeNews",
"props": {
"tag": "main"
}
}
],
}
]
}
編輯:所以我從其他模塊調用 function
await dataExtender(_schema);
其中包含一個功能(目前我正在開發它,但不完整)它是
const dataExtender = async _schema => {
// Define forEach function
console.log(chalk.green("Data Extending starts from module level"));
await Promise.all(
_schema.pages.forEach(async page => {
page.rows.forEach(row => {
row.column_1.forEach(async column => {
if (column.url !== undefined) {
await axios
.post(column.url, column.param || {})
.then(data => {
console.log(chalk.green("Extending"));
if (Array.isArray(data.data)) {
column.props.data = [...data.data];
} else {
column.props.data = { ...data.data };
}
})
.catch(err => {
console.log(err);
});
}
});
if (row.column_2 !== undefined) {
row.column_2.forEach(async column => {
if (column.url !== undefined) {
await axios
.post(column.url, column.param || {})
.then(data => {
column.props.data = data.data;
})
.catch(err => {
console.log(err);
});
}
});
}
});
}),
);
console.log(chalk.green("Data Extending finishes from module level"));
return _schema;
};
雖然forEach
本身不支持異步,但這並不能阻止您將異步修改承諾推送到列表中並在最后等待所有這些承諾。
import axios from "axios";
async function processColumn(column) {
const data = await axios.post(column.url, column.param || {});
console.log(chalk.green("Extending"));
if (Array.isArray(data.data)) {
column.props.data = [...data.data];
} else {
column.props.data = { ...data.data };
}
}
async function processColumn2(column) {
const data = await axios.post(column.url, column.param || {});
column.props.data = data.data;
}
const dataExtender = async (_schema) => {
console.log(chalk.green("Data Extending starts from module level"));
const promises = [];
_schema.pages.forEach((page) => {
page.rows.forEach((row) => {
row.column_1.forEach((column) => {
if (column.url !== undefined) {
promises.push(processColumn(column));
}
});
if (row.column_2 !== undefined) {
row.column_2.forEach((column) => {
if (column.url !== undefined) {
promises.push(processColumn2(column));
}
});
}
});
});
await Promise.all(promises);
console.log(chalk.green("Data Extending finishes from module level"));
return _schema;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.