ReactJS报错:更新深度超出最大值,日期选择器处理逻辑求助
Hey Maria-Elena, let's break down why you're hitting this infinite loop error and fix it step by step.
First, the root cause here is direct mutation of a prop (expData) inside your handleUpdate function. In React, props are designed to be read-only—changing them directly triggers unexpected re-renders of your component (and potentially its parent), which creates a cycle where the DatePicker's onUpdate fires repeatedly, leading to the "Maximum update depth exceeded" error.
Look at the problematic lines in your code:
expData['startDate'] = validDateStart expData['endDate'] = validDateEnd
When you mutate expData (a prop) like this, if expData is a state variable in the parent component, React detects the change and re-renders the parent. The parent then passes the updated expData back to your component, which triggers the DatePicker's update logic again—creating an infinite loop.
Here's how to fix it:
- Never modify props directly—create a copy of
expDatainstead, and use a callback from the parent component to update the state there. - Ensure state updates only happen when needed to avoid unnecessary re-renders.
Modified handleUpdate function:
const handleUpdate = (startDate, endDate) => { console.log(startDate, endDate); const { expData, onUpdateExpData } = props; // Create a copy of expData instead of mutating the original prop const updatedExpData = { ...expData, startDate: moment(startDate.timestamp).format('DD/MM/YYYY'), endDate: moment(endDate.timestamp).format('DD/MM/YYYY') }; // Let the parent component handle state updates via a callback onUpdateExpData(updatedExpData); // Close the date picker (safe since this updates local component state) setvisibleDatePicker(false); };
Parent component setup:
You'll need to add a callback in the parent component to update its state with the new expData values:
// In the parent component const [expData, setExpData] = useState(initialExpData); const handleExpDataUpdate = (updatedData) => { setExpData(updatedData); }; // Pass the callback to your component <YourDatePickerComponent expData={expData} onUpdateExpData={handleExpDataUpdate} // other props... />
Additional checks:
- Stick with
onUpdate={handleUpdate}(not the arrow function version) to avoid creating a new function on every render, which can trigger extra re-renders. - Confirm
setvisibleDatePickeris updating local component state (not a prop)—this part of your code looks fine, but ifvisibleDatePickeris controlled by a parent prop, adjust that logic to use a parent callback too.
By following these steps, you'll eliminate the infinite loop and align your component with React's one-way data flow rules.
内容的提问来源于stack exchange,提问作者Maria-Elena

