[英]change value of objects inside array of object with form input with React
Hi I'm new to react and I'm trying to make a workout tracker but I have become hardstuck on trying to capture the input of the exercises the way I'd like, as you can see by the many commented out code blocks I think that I'm missing something fundamental with useState maybe?嗨,我是 React 的新手,我正在尝试制作一个锻炼追踪器,但我一直坚持尝试以我喜欢的方式捕捉练习的输入,正如你可以从许多注释掉的代码块中看到的那样认为我可能缺少 useState 的一些基本知识?
this is my useState这是我的使用状态
const [formData, setFormData] = useState({
title: "",
date: "",
exercises: [{ Exercise: "benchpress", Reps: "5", Sets: "5" }],
});
this works with the title and date but i've tried many approaches and cant get it work with the object inside the exercise array这适用于标题和日期,但我尝试了很多方法,但无法让它与练习数组中的 object 一起使用
this is the onChange function on the form inputs这是表单输入上的 onChange function
const updateForm = (e) => {
setFormData((currentFormData) => ({
...currentFormData,
[e.target.name]: e.target.value,
}));
All the solutions I've tried has just led to adding whole new objects to the exercises array, or just adding the name + value in the original object next to the title and date.我尝试过的所有解决方案都只是将全新的对象添加到练习数组中,或者只是在标题和日期旁边的原始 object 中添加名称 + 值。
hey try like this it will update your exercise name and you can add more input fields to update more values嘿,像这样尝试它会更新你的练习名称,你可以添加更多输入字段来更新更多值
import * as React from 'react'
const Comp = () => {
const [formData, setFormData] = React.useState({
title: '',
date: '',
exercises: [{ Exercise: 'benchpress', Reps: '5', Sets: '5' }]
})
React.useEffect(() => {
console.log('gg', formData)
}, [formData])
const handle = (e, type) => {
console.log('gg', e)
setFormData({
title: formData.title,
date: formData.date,
exercises: [
{
Exercise: type === 'E' ? e : formData.exercises[0].Exercise,
Reps: type === 'R' ? e : formData.exercises[0].Reps,
Sets: type === 'S' ? e : formData.exercises[0].Sets
}
]
})
}
return (
<>
<input onChange={(e) => handle(e.target.value, 'E')} />
<input placeholder="rep" onChange={(e) => handle(e.target.value, 'R')} />
<input onChange={(e) => handle(e.target.value, 'S')} />
</>
)
}
Not the best way but it works For an array with large number of objects/feilds you should use map instead of hard coding them不是最好的方法,但它有效对于包含大量对象/字段的数组,您应该使用 map 而不是对它们进行硬编码
setFormData(formData.map((line, i) => {
line.title= "";
line.date="",
line.exercises.map((lineExerc, j) => {
lineExerc.name = e.target.value;
});
return line;
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.