Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

javascript - Cannot read property 'name' of undefined - react

I'm trying to work on the U of a CRUD app. My edit form keeps saying things are undefined. It is saying that "name" under the "medicine name" label is undefined.

import React, { useEffect, useState } from "react";
const EditMedicineForm = (props) => {
  const initialFormState = { id: null, name: "", directions: "" };
  const [medicine, setMedicine] = useState(props.currentMedicine);

  useEffect(() => {
    setMedicine(props.currentMedicine);
  }, [props]);

  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setMedicine({ ...medicine, [name]: value });
  };

  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        if (!medicine.name || !medicine.description) return;
        props.updateMedicine(medicine.id, medicine);
        setMedicine(initialFormState);
      }}
    >
      <label>medicine name</label>
      <input
        type="text"
        name="name"
        value={medicine.name}
        onChange={handleInputChange}
      />
      <label>directions</label>
      <input
        type="text"
        name="directions"
        value={medicine.directions}
        onChange={handleInputChange}
      />
      <button>Update medicine</button>
      <button
        onClick={() => props.setEditing(false)}
        className="button muted-button"
      >
        Cancel
      </button>
    </form>
  );
};
export default EditMedicineForm;
question from:https://stackoverflow.com/questions/65855562/cannot-read-property-name-of-undefined-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Before that use a property of object please check the object first. The object has to have content. Like this:

if (medicine && (!medicine.name || !medicine.description)){
  return; 
}

Look for that at your code and change them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...