[英]How to update nested data react
I am trying to build a form with some nested data update.我正在尝试构建一个包含一些嵌套数据更新的表单。 The code is as below:
代码如下:
On Change method改变方法
let student = {
name: null,
marks: { english: null },
};
const handleChange = (updatedValue) => {
student = {
...student,
...updatedValue,
marks: { ...updatedValue.marks },
};
console.log(student);
};
And my JSX:还有我的 JSX:
<input
type="text"
className="form-control"
id="name"
placeholder="Name"
value={student.name ?? ""}
onChange={(event) =>
handleChange({
name: event.target.value,
})
}
/>
<input
type="text"
className="form-control"
id="english"
placeholder="English"
value={student.marks.english ?? ""}
onChange={(event) =>
handleChange({
marks: { english: event.target.value },
})
}
/>
The problem is that for "name" it works fine.问题是对于“名称”它工作正常。 But for "english", it behaves abnormally.
但是对于“英语”,它的行为异常。 Eg when I enter "1" in English, it updates it to 1 in the console but on the UI, it immediately disappears from the input box.
例如,当我用英文输入“1”时,它会在控制台中将其更新为 1,但在 UI 上,它会立即从输入框中消失。 Also if I update it to 2, the value is replaced from one to 2.
此外,如果我将其更新为 2,则该值将从 1 替换为 2。
The the expected value is 1期望值为 1
Can someone please help me identifying how to update the nested values correctly from the input box?有人可以帮我确定如何从输入框中正确更新嵌套值吗?
you must use state to store data您必须使用 state 来存储数据
let student = {
name: null,
marks: { english: null },
};
change to改成
const [student, setStudent] = useState({
name: null,
marks: { english: null },
});
const handleChange = (updatedValue) => {
setStudent(student => ({
...student,
...updatedValue,
marks: { ...student.marks, ...updatedValue.marks },
}))
};
try this code试试这个代码
let student = {
name: null,
marks: { english: null },
};
const [name, setName] = useState("");
const [marks, setMarks] = useState("");
const handleChange = (data,updatedValue) => {
student = {
...student,
[data]:updatedValue
};
if(data==="name")
setName(updatedValue)
else
setMarks(updatedValue.english);
console.log(student);
};
and use this JSX并使用这个 JSX
<input
type="text"
className="form-control"
id="name"
placeholder="Name"
value={name}
onChange={(event) =>
handleChange("name",event.target.value)
}
/>
<input
type="text"
className="form-control"
id="english"
placeholder="English"
value={marks}
onChange={(event) =>
handleChange("marks", {
english:event.target.value})
/>
Hope this will give you output in your console.希望这会在您的控制台中为您提供 output。
And You need to use state to pass value
to the input.并且您需要使用 state 将
value
传递给输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.