在學生(兒童)組件中
useEffect
掛鉤將透過 handleStudentsChange
(父元件提供的函數)更新父數組。 在學生(家長)組件中
handleStudentsChange
函數使用 useCallback
掛鉤定義。然而,它似乎不起作用。 問題/疑問
handleStudentsChange
就會無限運行請參閱此處的程式碼: 我是 CodeSandBox 連結
Student.tsx(兒童)
import React, { useState, useEffect, useRef } from "react"; import TextField from "@mui/material/TextField"; interface student { firstName: string; lastName: string; grade: number; } interface studentProps { id: number; firstName: string; lastName: string; grade: number; handleStudentsChange: (index: number, student: student) => void; } function Student(props: studentProps) { const [firstName, setFirstName] = useState(props.firstName); const [lastName, setLastName] = useState(props.lastName); const [grade, setGrade] = useState(props.grade); useEffect(() => { handleStudentsChange(id, { firstName: firstName, lastName: lastName, grade: grade }); }, [firstName, lastName, grade, props]); return ( <> <TextField label="firstName" onChange={(event) => setFirstName(event.target.value)} value={firstName} /> <TextField label="lastName" onChange={(event) => setLastName(event.target.value)} value={lastName} /> <TextField label="grade" onChange={(event) => setGrade(+event.target.value)} value={grade} /> </> );
Students.tsx(父級)
import React, { useState, useCallback } from "react"; import Student from "./Student"; interface student { firstName: string; lastName: string; grade: number; } export default function Students() { const [students, setStudents] = useState<student[]>([ { firstName: "Justin", lastName: "Bieber", grade: 100 }, { firstName: "Robert", lastName: "Oppenhiemer", grade: 100 } ]); const handleStudentsChange = useCallback( (index: number, updatedStudent: student) => { // console.log(index) //I only want this to rerender when the value change however it turn into an infinity loop setStudents((prevStudents) => { const updatedStudents = [...prevStudents]; updatedStudents[index] = updatedStudent; return updatedStudents; }); }, [] ); return ( <> {students.map((student, index) => { return ( <Student key={index} id={index} firstName={student.firstName} lastName={student.lastName} grade={student.grade} handleStudentsChange={(index: number, newStudent: student) => handleStudentsChange(index, newStudent) } /> ); })} </> ); }
如上面的程式碼所示,我嘗試在學生(兒童)元件上使用React.memo
,並在handleStudentsChange
上使用useCallback
,希望能夠防止無限循環。然而,無限循環仍在持續。
問題
handleStudentsChange
不僅在發生更改時無限運行一次-它從第一次渲染開始就無限運行。這是因為Student
元件具有呼叫handleStudentsChange
的useEffect
,它更新了Students
元件中的狀態,導致Student
元件重新渲染,然後再次呼叫useEffect
,無限循環。解決方案
您需要在更新輸入後才呼叫
handleStudentsChange
,而不是每次渲染後都會呼叫。我在下面的範例中包含了一個範例,它在從輸入觸發blur
事件後更新了Students
中的狀態。對於更聰明(和複雜)的方法,您可以對比props和state來決定是否需要更新,但我將讓您自己解決。