React: Uncaught TypeError: Cannot destructure property 'id' of '_ref' as it is undefined

React: Uncaught TypeError: Cannot destructure property 'id' of '_ref' as it is undefined

几个小时以来我一直在努力解决这个问题,但我很困惑。根据控制台,当我发出补丁请求时,该请求通过并实际更新了信息,但之后我的地图功能出现故障并呈现空白页面。

这是有错误的组件:

import { useState, useEffect } from "react"
// import { EmployeeForm } from "./EmployeeForm"


export function EmployeeTable() {
    const [employees, setEmployees] = useState([])
    const [employeeId, setEmployeeId] = useState([])
    const [update, setUpdate] = useState(false)

    const [firstName, setFirstName] = useState('')
    const [lastName, setLastName] = useState('')

    useEffect(() => {
      fetch('/api/employees')
      .then(res => res.json())
      .then(json => setEmployees(json.employees)
      )
    }, [])

    const updateEmployee = async () => {
      try {
      const res = await fetch(`/api/employees/${employeeId}`, 
      {method: 'PATCH', body: JSON.stringify({firstName, lastName})})
      const json = await res.json()

      const employeesCopy = [...employees]
      const index = employees.findIndex((employee) => employee.id === employeeId)
      employeesCopy[index] = json.employee

      setEmployees(employeesCopy)
      setFirstName('')
      setLastName('')
      setUpdate(false)
      setEmployeeId([])
  } catch (err) {
      console.log(err)
  }
}

const submitForm = async (event) => {
  event.preventDefault()

  if(update){
      updateEmployee()
  }
}
    
  
const deleteEmployee = async (id) => {
  try {
      await fetch(`/api/employees/${id}`, {method: 'DELETE'})
      setEmployees(employees.filter(employee => employee.id !== id))
  } catch (error) {
      
  }
}
    const setEmployeeToUpdate = (id) => {
        const employee = employees.find(emp => emp.id === id)
        if(!employee) return
        setUpdate(true)
        setEmployeeId(employee.id)
        setFirstName(employee.firstName)
        setLastName(employee.lastName)
    }

    return (
        <div>
          <header>
            <h1>Employees</h1>
          </header>
          {employees.length > 0 ? (
            <table>
              <thead>
                <tr>
                  <th>First Name</th>
                  <th>Last Name</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {employees.map(({id, firstName, lastName}) => {
                  return(
                  <tr key={id}>
                    <td>{firstName}</td>
                    <td>{lastName}</td>
                    <td>
                        <button onClick={() => setEmployeeToUpdate(id)}>UPDATE</button>
                        <button onClick={() => deleteEmployee(id)}>DELETE</button>
                    </td>
                  </tr>
                  )
                })}
              </tbody>
            </table>
          ) : (
              // If for some reason the employees cannot be returned the page will render this p tag.
            <p>No employees</p>
            )}
                <form onSubmit={submitForm}>
            <div>
                <div>
                    <input type="text" value={firstName} onChange={e => setFirstName(e.target.value)}/>
                </div>
                <div>
                <input type="text" value={lastName} onChange={e => setLastName(e.target.value)}/>
                </div>
                <div>
                    <button type='submit'>{update ? 'Update' : 'Create'}</button>
                </div>
            </div>
        </form>
      </div>
      )
}

这里是 MirageJS server.js

import { createServer, Model } from "miragejs";
import faker from "faker";
import avatar from "./avatar.png";

export function makeServer({ environment = "test" } = {}) {
  let server = createServer({
    environment,
    models: {
      employee: Model,
    },
    seeds(server) {
      for (let i = 0; i < 10; i++) {
        server.create("employee", {
          id: faker.datatype.uuid(),
          firstName: faker.name.firstName(),
          lastName: faker.name.lastName(),
          email: faker.internet.email(),
          phone: faker.phone.phoneNumber(),
          bio: faker.lorem.paragraph(),
          avatar: avatar,
          address: {
            streetAddress: `${faker.address.streetAddress()} ${faker.address.streetName()}`,
            city: faker.address.city(),
            state: faker.address.stateAbbr(),
            zipCode: faker.address.zipCode(),
          },
        });
      }
    },
    routes() {
      this.namespace = "api";
      this.get(
        "/employees",
        (schema) => {
          return schema.employees.all();
        },
        { timing: 1000 }
      );
      this.patch(
        "/employees/:id",
        (schema, request) => {
          const attrs = JSON.parse(request.requestBody);
          const employee = schema.employees.find(request.params.id);
          employee.update(attrs);
        },
        { timing: 300 }
      );
      this.delete(
        "/employees/:id",
        (schema, request) => {
          const employee = schema.employees.find(request.params.id);
          employee.destroy();
          return new Response();
        },
        { timing: 300 }
      );
    },
  });
  return server;
}

提供一个默认值,从employees.map(({id, firstName, lastName}).

解构
{employees.filter(item => item).map(({ id = 0, firstName = 'empty', lastName = 'empty' }) => {...

setEmployees((prevState) => {
  const index = prevState.findIndex((employee) => employee.id === employeeId);
  let newEmployees = […prevState];
  newEmployees[index] = json.employee;
  return newEmployees;
}))

您在 server.js 补丁请求中错过了 return

server.js

this.patch(
     "/employees/:id",
        (schema, request) => {
          const attrs = JSON.parse(request.requestBody);
          const employee = schema.employees.find(request.params.id);
          return employee.update(attrs);
        },
     { timing: 300 }
 );