React 中的函数式组件不会随着 props 的变化而更新

时间:2021-03-18 09:01:53

标签: reactjs react-router react-hooks

我是新来的,我创建了一个 listContactComp 来显示列表,它有编辑按钮到那个特定的元素。 在单击编辑按钮时,我正在调用 editContactComp,它将 id 作为道具并获取特定的联系人数据。

它被获取但不会在表单中更新。

这里是editContactComp.js的代码

import React from 'react'
import { useRouteMatch} from "react-router-dom";
import ContactForm from "./ContactForm";

const EditContact = () => {
    const stateData = useRouteMatch();
    const contactId = stateData.params.contactId;
    console.log("insurer -> ", contactId);  //  gets printed
    const defContactData = {
        name: "",
        email: "",
        phone: "",
        status: false,
        address: ""
    }

    const [formDataUpdate, setContactData] = React.useState(defContactData);

    React.useEffect(() => {
        const fetchContact = async () => {
            const response = await fetch(`http://localhost:3008/fetchContact?id=${contactId}`);
            const contacts = await response.json();
            console.log("contact data ", contacts.data[0]);    // data is coming in array, oneElement
            setContactData(contacts.data[0]);
        }
        fetchContact();
    }, [contactId])

    const updateInsurer = async (contactData) => {
        console.log("edit contact");
        // update logic
    }

    return (
        <>
            <ContactForm contact={formDataUpdate} onSubmit={updateInsurer} />
        </>
    )
}

export default EditContact;

联系表格是:

const ContactForm = ({ contact, onSubmit }) => {
    console.log("from props ", contact);    // whole data is printed here
    const [formData, setFormData] = React.useState(contact);
    console.log("insurer form values", formData);   // only default data is printed here and shown in form

    return (
        <>
        ... whole form body
        </>
    )
}

export default ContactForm;

1 个答案:

答案 0 :(得分:1)

正如@rdr20 建议的那样:尝试使用 contact 挂钩侦听 <ContactForm />useEffect() 上的更改。

const ContactForm = ({ contact, onSubmit }) => {
    const [formData, setFormData] = React.useState(contact); // this runs only once, when the component is mounted, not when i.e. contact updates.
    
    useEffect(() => {
        setFormData(contact);
        }, [contact]) // now this listens to changes in contact

    return (
        <>
        ... whole form body
        </>
    )
}

export default ContactForm;