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
3.7k views
in Technique[技术] by (71.8m points)

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

very, very new to React. first stack overflow post.

been coding over 12 hrs, probably a small mistake. 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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...