【发布时间】:2020-07-01 02:44:47
【问题描述】:
父组件包含一个对象数组。 它映射数组并为每个对象返回一个子组件,并用该对象的信息填充它。 在每个子组件内部都有一个输入字段,我希望它允许用户更新对象,但我不知道如何去做。 在钩子、道具和对象不变性之间,我在概念上迷失了方向。 这是父组件的简化版本:
const Parent = () => {
const [categories, setCategories] = useState([]);
useEffect(()=>{
// makes an axios call and triggers setCategories() with the response
}
return(
categories.map((element, index) => {
return(
<Child
key = {index}
id = {element.id}
firstName = {element.firstName}
lastName = {element.lastName}
setCategories = {setCategories}
})
)
}
这是子组件的简化版本:
const Child = (props) => {
return(
<h1>{props.firstName}</h1>
<input
defaultValue = {props.lastName}
onChange={()=>{
// This is what I need help with.
// I'm a new developer and I don't even know where to start.
// I need this to update the object's lastName property in the parent's array.
}}
)
}
【问题讨论】:
-
请提供minimal reproducible example,但请注意,这不是教程服务。
-
忘记这个钩子,你知道如何以不可变的方式更新数组中的对象吗?
-
@jonrsharpe 我刚刚更新了它。希望这会有所帮助。我是开发和 Stack Overflow 的新手,所以我仍然习惯于如何提出好的问题。
-
见meta.stackoverflow.com/q/284236/3001761;如果您不知道从哪里开始,结构化教程可能是比 SO 问题更好的选择。
-
不,不要删除您的问题,这很好。如果你认为你知道如何更新数组,并且不可变地发布代码,那么我们可以看到你哪里出错了。如果您遇到错误,请发布该错误
标签: arrays reactjs object react-hooks parent-child