gpt4 book ai didi

javascript - 如何避免在for循环完成之前调用.map函数?

转载 作者:行者123 更新时间:2023-12-02 21:17:34 25 4
gpt4 key购买 nike

我有一个函数handleForm(formData):

    handleFormData(formData) {
const { school, schoolyear } = this.props.params;
const { addDataToBackend } = this.props;
const { selectedDate } = this.props.schoolVacationDelivery;

if (!_.isEmpty(selectedDate)) {
var structuredFormData = [];
for (var key in formData) {
var prefix = key.split("=")[0];
var appendix = key.split("=")[1];
var dataObject = structuredFormData.find(o => o.season === prefix);
if (!dataObject) {
dataObject = { season: prefix };
structuredFormData.push(dataObject);
}
dataObject[appendix] = formData[key];
}

let updatedStructuredFormData = structuredFormData.map(x => {
let season = x.season;
x.date = selectedDate.find(e => e.indexOf(season) > -1).split("=")[1];
return x;
});

addDataToBackend(schoolyear, updatedStructuredFormData);
} else {
addDataToBackend(schoolyear, []);
}

browserHistory.push(
`/schooladmin/home/school/${school}/schoolyear/${schoolyear}/prepackaged`
);
}

有时我会在这一行得到Cannot read property 'split' of undefined x.date = selectedDate.find(e => e.indexOf(season) > -1 ).split("=")[1];。我如何确保在 for 循环完成之前不会调用 structuralFormData.map ?我如何更改代码,以便始终确保 for 循环在调用 structuralFormData.map 函数之前结束?

这是错误输出:

enter image description here

第 98 行:let UpdatedStructuredFormData = StructuredFormData.map(x => { ..

第 100 行:x.date = selectedDate.find(e => e.indexOf(season) > -1).split("=")[1];

最佳答案

您的 for 循环不包含任何异步操作(例如 API 请求、setTimeout、promise 等),因此 JavaScript 始终会在 .map.

看来您的问题不在 handleFormData 函数之外(例如,您在函数内部使用的 props 中的数据)。

检查您如何获取此数据,并在需要时再次寻求帮助。祝你好运!

关于javascript - 如何避免在for循环完成之前调用.map函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60929864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com