我必须使用 React 中的 useState 挂钩将对象列表存储在数组中。我有带有 onChange 的输入字段,我得到了它的值并尝试在列表中的一个对象中放置/更新它。输入在一个类似结构的表格中,每一行代表一个集合。每列是代表次数、rpe 和重量。这些值属于每个集合,需要保存在数组中的一个对象中。目前,当您编辑时,它不会保存您所做的所有事情,而只会保存您在该行中所做的最后一件事。
const [sets, setSets] = useState([]);
const [numSets, setNumSets] = useState(1);
const [tableSets, setTablesSets] = useState([]);
const repsOnChangeHandler = index => e => {
e.preventDefault();
//let x = tableSets.push(value);
console.log(index)
let tempArray=[...tableSets];
tempArray[index] = {...tempArray[index], reps: e.target.value}
setTablesSets(tempArray);
}
const rpeOnChangeHandler = index => e => {
e.preventDefault();
//let x = tableSets.push(value);
let tempArray=[...tableSets];
tempArray[index] = {...tempArray[index], rpe: e.target.value}
setTablesSets(tempArray);
}
const weightOnChangeHandler = index => e => {
e.preventDefault();
//let x = tableSets.push(value);
let tempArray=[...tableSets];
tempArray[index] = {...tableSets[index], weight: e.target.value}
setTablesSets(tempArray);
}
const addSetHandler = () => {
let temp = {
reps: 0,
rpe: 0,
weight: 0
};
setTablesSets(tableSets.concat(temp));
let x = numSets;
setNumSets(x + 1);
setSets([...sets, {
id: sets.length,
setValue: <li key={sets.length} className={classes.TableRow}>
<input type="number" min="1" readOnly="readonly" className={classes.TableInput} value={numSets} />
<input type="number" min="1" max="40" className={classes.TableInput} onChange={repsOnChangeHandler(numSets-1)} />
<input type="number" min="1" max="10" className={classes.TableInput} onChange={rpeOnChangeHandler(numSets-1)} />
<input type="number" min="1" className={classes.TableInput} onChange={weightOnChangeHandler(numSets-1)} />
</li>
}]);
}