React:更新对象数组的特定属性

React: Update a specific attribute of an array of objects

我有一个相当简单的要求,但结果对我来说却相当复杂。我正在开发一个基本的待办事项应用程序 UI:

Design

现在我需要更新对象数组,以便只更新特定项目的文本。这是我的尝试,但它只是在每次按键时添加一个新组件:

import React, {useState} from "react";

const DynamicInput = () => {
  const [todos, setTodos] = useState([])
  
  
  const onAddClick = () => {
    setTodos(prevState => {
      return [...prevState, {id: prevState.length + 1, text: "", up: "↑", down: "↓", del: "x"}]
    })
  }
  
  const onValueUpdate = (id) => (event) => {
    let tempObject = todos[id]
    
    setTodos(prevState => {
    return [...prevState, {
        id: id,
        text: event.target.value,
        up: "Up",
        down: "Down",
        del: "x"
        }];  
    })

  }
  
  const onUpArrow = (event) => {
    console.log("On up")
  }
  
  const onDownArrow = (event) => {
    console.log("On down")
  }
  
  const onDeleteArrow = (event) => {
    console.log("On delete")
  }
  
  return (
    <>
      <button onClick={onAddClick}>+</button>
      {todos.map(todo => {
        return( 
          <div key={todo.id}>
            <input onChange={onValueUpdate(todo.id)} value={todo.text}></input>
            <button onClick={onUpArrow}>{todo.up}</button>
            <button onClick={onDownArrow}>{todo.down}</button>
            <button onClick={onDeleteArrow}>{todo.del}</button>
          </div>)
      })}
    </>
  );
};
export default DynamicInput;

为了简单地解决您的问题,您可以将 onValueUpdate() 方法更改为:

const onValueUpdate = (id) => (event) => {
    setTodos(prevState => {
        let data = [...prevState];
        let indexOfTodo = data.findIndex(todo => todo.id === id);
        data[indexOfTodo] = {
            ...data[indexOfTodo],
            text: event.target.value,
        };
        return data;
    });
};