嗨,我试图为每个输入字段显示加载器,但只有当它们输入值时。我得到的行为是,如果我输入一个值到一个文本输入的旋转显示为所有。我需要根据两个数组的差异,通过数组键来确定我的加载状态。
类似此文->如何在JavaScript中获得两个对象数组之间的差异
const [isLoading, setIsLoading] = useState('');
// before any value has been entered
const initialFormData = [{key: 'USER_DEFINED_QUESTIONS', value: ''}, {key: 'RECOMMENDED_FIELDS', value: ''}]
// when a value has been entered
const values = [{key: 'USER_DEFINED_QUESTIONS', value: 'test'}, {key: 'RECOMMENDED_FIELDS', value: ''}]
const saveSubmit = async (values) => {
const arrValues = Object.entries(values).map((val) => ({
field: val[0],
value: val[1],
}));
const arrInitialFormValues = Object.entries(initialFormData).map(
(val) => ({
field: val[0],
value: val[1],
}),
);
const result = arrValues.filter(
(o1) => !arrInitialFormValues.some((o2) => o1.key === o2.key),
);
const body = { ...values };
setIsLoading(result);
const res = await putResults({ id, body });
if (res && !(await checkErrors(res))) {
return res;
}
setIsLoading(result);
}
return null;
};
您可以将重命名和过滤器
结合使用const saveSubmit = async (values) => {
const result = initialFormData.reduce((acc, a) => {
const diff = values.find((b) => a.key === b.key && a.value !== b.value)
return diff
? [
...acc,
{
field: diff.key,
value: diff.value,
},
]
: acc
}, [])
const body = { ...values }
setIsLoading(result)
const res = await putResults({ id, body })
if (res && !(await checkErrors(res))) {
return res
}
setIsLoading(result)
}
首先,我将数组映射到一个对象(这是不需要的,只是这样感觉更干净)。
values = Object.fromEntries(a.map(entry => [entry.key, entry.value]))
那么我相信,你真正需要做的就是找到所有具有非负"值"的项。(如果不是这样,请在下面评论,我将纠正这个答案)。
usedFields = Object.entries(values).filter(entry => entry[1])
如果您只想获得差异,这就是我可以从问题标题中读取的内容,不应该这样做吗?
const initialFormData = [{key: 'USER_DEFINED_QUESTIONS', value: ''}, {key: 'RECOMMENDED_FIELDS', value: ''}];
// when a value has been entered
const values = [{key: 'USER_DEFINED_QUESTIONS', value: 'test'}, {key: 'RECOMMENDED_FIELDS', value: ''}];
const keysWhichDiffer = values.map(x => initialFormData.find(y=> x.key===y.key && x.value!==y.value)?.key);
const result = keysWhichDiffer.filter(x=>x);
console.log('res', result)