如何使用useState更改数组中的单个元素

问题描述

我的程序应该允许用户输入多个等级并根据需要更改每个等级。我在更新数组中的单个元素时遇到问题。这是我的主要功能

iterator

这是我将钩子传递给的函数

const_iterator

解决方法

我相信您不能以这种方式直接在 onChange 处理程序中调用 setGrade。

您应该创建一个名为 handleSetGrades 的函数并使用对输入的引用:

import React,{useRef} from "react";
export default function NewGradeRow({ number,grade,setGrade }) {
    // here we access the value of grade using a reference
    const gradeRef = useRef();

    function handleSetGrades()={
        // here we call the setGrade prop that was passed down to this component
        // setting the value based on the current value of our input ref
        
        // use function notation here to get the current state of grades
        setGrade((grades)=>{
             // number is always one greater than the index of the grade we are interested in.
             const indexOfGrade = number-1;
             // make a copy of the grades array 
             let temp = grades;
             // set the value to the new value
             temp[indexOfGrade] = gradeRef.current.value;
             return temp
        });
    }

    return(
        <tr>
            <td>{number}</td>
            <td>
                <form>
                    <input ref={gradeRef} type="number" id="Grade" name="Grade" value={grade}
                           onChange={handleSetGrades}/>
                </form>
            </td>
        </tr>
    )
}