繁体   English   中英

如何使用组件的方法更改另一个组件中的 object? [反应]

[英]How to use a component's method to alter an object in another component? [React]

我有一个简单的应用程序,其中有 3 个 React 组件堆叠在另一个组件之上:

function App() {
  return (
    <Fragment>
      <div className="container">
        <ListSuppliers/>
        <InputContact/>
        <ListContact/>
      </div>

    </Fragment>
  );
}

在我的ListSuppliers组件中,我有一个下拉菜单,在我的InputContact组件中,我有一个输入表单,在我的ListContact中,我有一个 html 表,如下所示:

return <Fragment>
        <h1>List Contact</h1>

        <table className="table mt-5">
            <thead>
                <tr>
                    <th>Contact Name</th>
                    <th>Edit</th>
                    <th>Delete</th>
                </tr>
            </thead>
            <tbody>
                {contacts.map(contact => (
                    <tr key={contact.contact_id}>
                        <td>{contact.contact_name}</td>
                        <td><EditContact contact={contact}/></td>
                        <td><button className="btn btn-danger" onClick={()=> deleteContact(contact.contact_id)}>Delete</button></td>
                    </tr>
                ))}
                
                  
            </tbody>
  </table>

    </Fragment>

我希望根据ListSuppliers组件中的菜单选择填充ListContact组件中的 html 表:

//Select function

    const chooseSupplier = async (id) => {
        try {
            const response = await fetch(`http://localhost:5000/contact_supplier/${id}`,{
                method: "GET"
            });

            const jsonData = await response.json();

            
            console.log(jsonData);
            
        } catch (err) {
            console.log(err.message);
        }
    }

//Route

app.get("/contact_supplier/:id", async (req, res) => {
    try {

        const {id} = req.params;
        const contact = await pool.query('SELECT * FROM contact WHERE supplier_id = $1 ORDER BY contact_id ASC', [id]);


        res.json(contact.rows);

    } catch (err) {
        console.error(err.message);
    }
})

到目前为止,我能够以 json 格式接收我需要的查询,但是在这种情况下,我不确定如何从一个组件目标查询到另一个组件目标 object。

您需要在父组件(此处 - App.js)中为const [state,setState] = useState() ,然后将statesetState传递给子组件,以便他们可以访问并调用它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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