简体   繁体   中英

Update property of hooks in another component

Here is a simplified version of my react code. I have a hook like this:

const [todo, setTodo] = useState();

My todo looks like this:

todo = {
    name: 'Name of my todo list',
    date: 2022-09-19',
    todos: [
        'groceries', 
        'do the laundry'
    ]
}

In my main component I pass to "todos component" the todos:

In my todos component, I have a loop on the props to show all input with todos value

{todos.map(t => {
   <input 
       value={t} 
       onChange={e => {
           t = e.target.value
       }} 
   />
})

But unfortunately it doesn't update the todo. How do I do this? I cannot use setTodo because I'm in the child component and setTodo manage all the todo object whereas I just want to update the list of todo. My component doesn't have knowledge of the full todo object but just the list of todo.

I cannot use setTodo

You must. That is the only way to change the state.

However, you don't necessarily need to use it directly in the child component. It makes total sense to want to limit the child component so it doesn't need to know about the entire todo object. To do this, you can pass down a function that knows how to do most of the update, and then have the child component call that, passing in the few pieces of information that the child is in charge of.

For example:

const Parent = () => {
  const [todo, setTodo] = useState();

  return (
    <Child 
      todos={todos} 
      onChange={(newValue, index) => {
        setTodo(prev => {
          const newArray = [...prev.todos];
          newArray[index] = newValue;
          return {
            ...prev,
            todos: newArray
          };
        });
      })
    />
  );
}

const Child = ({ todos, onChange }) => {
  // ...

  {todos.map((t, i) => {
    <input 
      value={t} 
      onChange={e => {
        onChange(e.target.value, i);
      }} 
    />
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM