【发布时间】:2020-02-03 08:56:41
【问题描述】:
我必须使用 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>
}]);
}
【问题讨论】:
-
不,那行不通。你必须像我那样做才能获得活动
-
准备 minimal reproducible example 在代码沙箱上?
-
输入中没有实际的
value? -
我得到的值是正确的,当我尝试编辑状态时,它似乎只是擦除了状态。我想我遇到的主要问题是试图编辑例如代表列表中的第一个对象
-
console.log(index)显示...?
标签: javascript reactjs input onchange use-state