简体   繁体   中英

How can I safely set new state of a component when props change with useEffect (for an edit form modal component)?

I have a modal form component that allows a user to edit a row in a table. I update the state like this when the editing object changes.

const [form, setForm] = useState(editObj);
useEffect(() => {
    setForm(editObj);
}, [editObj]);

For context, the parent component has a table with an "edit" link that does this:

onClick={() => {
  setEditObj(record);
  setModalOpen(true);
}}

The reason I need this to be part of the state is that the user can edit it via a form, but this is a copy of the original record (And if the user presses "cancel" in the modal and then clicks on another row, the previous object is forgotten).

From what I understand, this useEffect should not cause an infinite loop because the deps specified [editObj], which only changes when the user clicks edit in a different row.

Interestingly, this actually works as expected when I'm on this screen, but when I leave this screen is when it actually triggers an infinte loop. I don't understand this.

Solution: don't render modal if the modal is not visible:

{isModalOpen && (
  <EditModal
    editObj={editObj}
    visible={isModalOpen}
    onClose={() => setModalOpen(false)}
  />
)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM