我想出了一个解决方案,用于更改 React 中二级嵌套状态的属性,该状态不可扩展,而且似乎效率不高。您如何对handleOnChange
方法进行重构以更改reps
和weight
?
import React, { useState } from "react";
const workout = {
id: "123-234sdf-1213",
name: "wo name",
done: false,
exercises: [
{
name: "back squat",
sets: [
{
number: 0,
reps: 0,
weight: 0,
done: false,
},
{
number: 1,
reps: 0,
weight: 0,
done: false,
},
{
number: 2,
reps: 0,
weight: 0,
done: false,
},
],
},
{
name: "leg press",
sets: [
{
number: 0,
reps: 0,
weight: 0,
done: false,
},
{
number: 1,
reps: 0,
weight: 0,
done: false,
},
{
number: 2,
reps: 0,
weight: 0,
done: false,
},
],
},
],
};
export default function App() {
const [workoutState, setWorkoutState] = useState(workout);
const handleOnChange = (e, exIndex, setIndex) => {
const value = e.target.value ? parseFloat(e.target.value) : "";
const exercises = [...workoutState.exercises];
exercises[exIndex].sets[setIndex] = {
...exercises[exIndex].sets[setIndex],
[e.target.name]: value,
};
setWorkoutState({
...workoutState,
exercises,
});
};
return (
<div className="App">
<h1>{workoutState.name}</h1>
{workoutState.exercises.map((ex, exIndex) => (
<>
<h2>{ex.name}</h2>
{ex.sets.map((set, setIndex) => (
<div key={`${ex.name}_${setIndex}`}>
<div>
reps:{" "}
<input
value={set.reps}
name="reps"
type="number"
onChange={(e) => handleOnChange(e, exIndex, setIndex)}
/>
</div>
<div>
weight:{" "}
<input
value={set.weight}
name="weight"
type="number"
onChange={(e) => handleOnChange(e, exIndex, setIndex)}
/>
</div>
</div>
))}
</>
))}
</div>
);
}