小编squ*_*ers的帖子

使用 React 钩子,如何更新通过道具传递给孩子的对象?

父组件包含一组对象。它映射数组并为每个对象返回一个子组件,用该对象的信息填充它。在每个子组件内都有一个输入字段,我希望它允许用户更新对象,但我不知道如何去做。在钩子、道具和对象不变性之间,我在概念上迷失了。这是父组件的简化版本:

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}
    })
  )
}
Run Code Online (Sandbox Code Playgroud)

这是子组件的简化版本:

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 …
Run Code Online (Sandbox Code Playgroud)

arrays object parent-child reactjs react-hooks

2
推荐指数
1
解决办法
1369
查看次数

标签 统计

arrays ×1

object ×1

parent-child ×1

react-hooks ×1

reactjs ×1