使用React钩子,如何更新通过props传递给孩子的对象? [英] Using React hooks, how can I update an object that is being passed to a child via props?

查看:56
本文介绍了使用React钩子,如何更新通过props传递给孩子的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The parent component contains an array of objects. It maps over the array and returns a child component for every object, populating it with the info of that object. Inside each child component there is an input field that I'm hoping will allow the user to update the object, but I can't figure out how to go about doing that. Between the hooks, props, and object immutability, I'm lost conceptually. Here's a simplified version of the parent component:

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}
    })
  )
}

这是子组件的简化版本:

And here's a simplified version of the child component:

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.
      }}
  )
}

推荐答案

也许不知道,您已经解除了状态:基本上,而不是将状态保留在 Child 组件,将其保留在 Parent 中.
这是一个使用过的模式,没有什么错:您只是错过了一个让孩子们更新 Parent 的状态的handle函数:为此,您需要实现一个 Parent 组件上的handleChange ,然后将其作为道具传递给每个 Child .

Maybe without knowing it, you have lifted the state: basically, instead of having the state in the Child component, you keep it in the Parent.
This is an used pattern, and there's nothing wrong: you just miss a handle function that allows the children to update the state of the Parent: in order to do that, you need to implement a handleChange on Parent component, and then pass it as props to every Child.

看看下面的代码示例:

const Parent = () => {
    const [categories, setCategories] = useState([]);

    useEffect(() => {
        // Making your AXIOS request.
    }, []);

    const handleChange = (index, property, value) => {
        const newCategories = [...categories];
        newCategories[index][property] = value;

        setCategories(newCategories);
    }

    return categories.map((c, i) => {
        return (
            <Child
                key={i}
                categoryIndex={i}
                firstName={c.firstName}
                lastName={c.lastName}
                handleChange={handleChange} />
        );
    });
}

const Child = (props) => {
    ...

    const onInputChange = (e) => {
        props.handleChange(props.categoryIndex, e.target.name, e.target.value);
    }

    return (
        ...
        <input name={'firstName'} value={props.firstName} onChange={onInputChange} />
        <input name={'lastName'} value={props.lastName} onChange={onInputChange} />
    );
}

您可能不知道的几件事:

Few things you may not know:

  • 通过对 input 使用属性 name ,您可以对所有 input 元素仅使用一个处理函数.在函数内部,在这种情况下为 onInputChange ,您可以使用 e.target.name ;
  • 检索该信息.
  • 请注意,我在您的 useEffect 中添加了一个空数组依赖项:没有它, useEffect 将在每次渲染时都运行.我认为那不是您想要的.
    相反,我邀请您,您只想在挂载组件时才执行请求,并且可以通过n个空数组依赖项来实现;
  • By using the attribute name for the input, you can use just one handler function for all the input elements. Inside the function, in this case onInputChange, you can retrieve that information using e.target.name;
  • Notice that I've added an empty array dependecies in your useEffect: without it, the useEffect would have run at EVERY render. I don't think that is what you would like to have.
    Instead, I guest you wanted to perform the request only when the component was mount, and that is achievable with n empty array dependecies;

这篇关于使用React钩子,如何更新通过props传递给孩子的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆