Welcome to OGeek Q&A 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...