我有一個形式,即填充在18個孔上的高爾夫球場,每個孔的具有以下欄位,hole,par,stroke,yards,courseid
當填寫每個輸入欄位時,它會觸發 onChange 并將表單狀態中的變數值設定為輸入欄位值。
在我的表單物件中,我有所有這些欄位,
const [form, setForm] = useState([
{
hole1: 1,
par1: '',
stroke1: '',
yards1: ''
},
{
hole2: 2,
par2: '',
stroke2: '',
yards2: ''
},
{
hole3: 3,
par3: '',
stroke3: '',
yards3: ''
},
//repeated for 18 holes
當完成并點擊提交時,它會觸發保存功能,一個串列被發送到后端(SpringBoot)以dB保存。
由于有 18 個孔,我需要遍歷資料,以便我可以填充 18 個物件以放入串列以發送到后端。
我做了一個holes物件
let[holes, setHoles] = useState({
"hole": '',
"par": '',
"stroke": '',
"yards": '',
"course": {
"courseid": ''
}
});
我現在想用form資料中的值填充它。
所以我想將holes每個欄位的值設定為,
form.hole1,
form.par1,
form.stroke1,
form.yards1
Then add that holes object to the list, then run the loop again and add all the values for hole 2, etc etc until all 18 holes are done.
When using a loop like,
for (let i= 1; i< 19; i ) {
holes = {
"hole": index,
"par": form.par,
"stroke": form.stroke,
"yards": form.yards,
"course": {
"courseid": 3
}
}
const newList = list.concat({holes})
list = newList;
};
how is it best to tell it to take form.par1 on the first loop, then form.par2 on the second loop etc.
I feel like I need two loops running here, so that it starts off looping through all the numbers 1-18, and before moving to the next number it loops through the objects in the form,
so it starts at hole 1, get the holes object, gets the value from the first form object, sets the 4 fields in holeto those in the firstform object i.e par1, yards1 etc, then concats the hole object to the list then moves on to the number 2 and continues this till all 18 are complete, but I am not sure how I can achieve this.
uj5u.com熱心網友回復:
鑒于form您所描述的陣列形狀,您可以將其映射到所需list的孔,如下所示:
const list = form.map((hole, i) => {
const num = i 1;
return {
hole: num,
par: hole[`par${num}`],
stroke: hole[`stroke${num}`],
yards: hole[`yards${num}`],
course: {
courseid: 3,
},
};
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347925.html
上一篇:這個回圈是如何作業的?我無法理解
下一篇:從串列中選擇隨機函式
