You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React报错:Uncaught TypeError: 无法解构undefined的'_ref'的'id'属性——Patch请求成功后Map函数失效致页面空白

Hey there, let's dig into why your page goes blank after the PATCH request. I spotted two key issues in your code that are causing this:

1. MirageJS PATCH route isn't returning the updated employee

Your Mirage server successfully updates the employee data when handling the PATCH request, but it doesn't send the updated employee object back to the frontend. In your updateEmployee function, you're trying to use json.employee to update your local state—but since the response doesn't include this data, json.employee becomes undefined.

When you replace an item in your employeesCopy array with undefined, the subsequent map function tries to access properties like id, firstName, and lastName on that undefined value. This throws a JavaScript error that crashes the component, resulting in a blank page.

Fix: Update your Mirage PATCH route to return the modified employee:

this.patch(
  "/employees/:id",
  (schema, request) => {
    const attrs = JSON.parse(request.requestBody);
    const employee = schema.employees.find(request.params.id);
    employee.update(attrs);
    // Return the updated employee so the frontend can use it
    return employee;
  },
  { timing: 300 }
);

2. Mismatched initial state type for employeeId

You initialized employeeId as an empty array ([]), but your employee IDs are string-based UUIDs. While setEmployeeToUpdate corrects this by setting it to a string later, the initial type mismatch could cause unexpected behavior (like failed findIndex comparisons in edge cases).

Fix: Set employeeId's initial state to a type that matches your actual IDs:

const [employeeId, setEmployeeId] = useState(undefined);
// Or alternatively:
// const [employeeId, setEmployeeId] = useState('');

And update the reset logic in updateEmployee to match:

setEmployeeId(undefined); // Or ''

Bonus: Add a safety check for missing employees

To avoid further crashes if an employee can't be found, add a check before updating your state array:

const index = employees.findIndex((employee) => employee.id === employeeId);
// Only update if we found a matching employee
if (index !== -1) {
  employeesCopy[index] = json.employee;
  setEmployees(employeesCopy);
}

内容的提问来源于stack exchange,提问作者Casey MacLeod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 09:28:12