React JS通过API将array.map值存入数据库不同列的问题
问题描述
勾选复选框分类选项后,需要将所有选中项的对应值分别存入数据库的不同独立列中。
当前通过以下代码遍历获取选中项名称集合:
const checkListNames = check.map((item) => item.name)
得到的输出结果示例:
['需要配备舞台', '主题装饰是我的活动必备项']
现有表单提交逻辑未实现分字段存储效果,已编写的handleSubmit提交代码如下:
const handleSubmit = (e) => { e.preventDefault(); if (check.length > 0) { const checkListNames = check.map((item) => item.name); let formData = new FormData(); formData.append('list_category', categoryId); formData.append('name', checkListNames); formData.append('event_id', get_all_data.data7); formData.append('created_by', '629829078779cc4a00139c9a'); for (var pair of formData.entries()) { console.log(pair[0] + ' - ' + pair[1]); } api .post('checklist', formData) .then((response) => { const { data } = response; if (data.status == '1') { toast.success('Checklist added successfully'); history.push('/CheckList'); } else { toast.error('Something went wrong !'); } }) .catch((error) => { throw error; }); } else { toast.error('Select atleast one category'); return false; } };
解决方法
原逻辑的核心问题是直接把整个选中值数组赋值给了单个name字段,后端拿到的是单字段的数组值,无法拆分存入不同列,按以下方式修改即可:
- 提前和后端确认数据库存储复选框选项的独立列字段名,按复选框的固定展示顺序整理为列名数组
- 删除原代码中将整个
checkListNames数组追加到name字段的逻辑 - 遍历列名数组,按索引依次取出对应位置的选中值追加到FormData对应字段;如果选中项数量少于列数,给未匹配到的字段传空值,避免后端报字段缺失错误
修改后的提交代码参考:
const handleSubmit = (e) => { e.preventDefault(); if (check.length > 0) { const checkListNames = check.map((item) => item.name); let formData = new FormData(); formData.append('list_category', categoryId); formData.append('event_id', get_all_data.data7); formData.append('created_by', '629829078779cc4a00139c9a'); // 替换为实际数据库对应列名,顺序和复选框选项顺序保持一致 const dbColumns = ['need_stage', 'need_theme_decor', 'need_photography', 'need_catering']; // 遍历列名,依次将选中值存入对应字段,无匹配值则传空 dbColumns.forEach((columnKey, index) => { formData.append(columnKey, checkListNames[index] ?? ''); }); for (var pair of formData.entries()) { console.log(pair[0] + ' - ' + pair[1]); } api .post('checklist', formData) .then((response) => { const { data } = response; if (data.status == '1') { toast.success('Checklist added successfully'); history.push('/CheckList'); } else { toast.error('Something went wrong !'); } }) .catch((error) => { throw error; }); } else { toast.error('Select atleast one category'); return false; } };
注意:如果复选框的渲染顺序不固定,不要靠索引匹配字段,建议给每个复选框选项提前绑定对应的数据库字段名,选中后直接按选项自带的字段名存值,避免顺序错乱导致数据存错列。
内容的提问来源于stack exchange,提问作者Nidhi Mahajan
相关产品推荐
相关产品推荐

