【发布时间】:2023-01-20 03:22:47
【问题描述】:
我正在尝试更新用户对象中的单个键/值对,该对象包含另一个名为“教育”的对象数组。我在列表组件上设置了一个名为“index”的自定义属性,以便在更新时访问数组索引。
// User object
const [userData, setUserData] = useState({
firstName: '',
lastName: '',
title: '',
email: '',
phoneNumber: '',
website: '',
bio: '',
education: [
{
id: uniqid(),
school: '',
degree: '',
city: '',
state: '',
timeframe: ''
}
]
})
// Render input form for Education
const listItems = props.userData.education.map((user, index) => {
return (
<div key={index}>
<h2>University/School #{index}</h2>
<input
type="text"
index={index}
placeholder="Your school"
name="school"
onChange={props.handleChange}
value={props.userData.education[index].school}
/>
</div>
);
});
为 onChange 创建了这个函数处理程序,但它只返回一个空字符串并且不更新对象。我觉得我在这里错误地使用了传播运算符,但无法弄清楚如何正确地将它们组合在一起。
// Update user education state
const handleChange = (e) => {
const { value, name } = e.target
const index = e.target.getAttribute('index')
setUserData(prevUser => ({
...prevUser,
[prevUser.education[index]]: {
[name]: value
}
}))
}
【问题讨论】:
标签: javascript reactjs react-hooks