React组件中调用双API并展示getData接口返回的联系人数据的实现方案咨询
Solution to Display Contact Data from
/api/contact Got it, let's get your contact name and number showing up in that designated div. The core idea is to store the contact data you fetch from /api/contact in component state, then reference that state in your render output. Here's a step-by-step implementation:
Step 1: Add State Variables
First, add state to hold your contact data, plus loading/error states for better UI feedback:
const [contact, setContact] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null);
Step 2: Update the getData Function
Modify getData to update state with the fetched contact data, and handle loading/errors:
const getData = async () => { try { const result = await axios.get("api/contact"); setContact(result.data); // Assumes API returns an object with name/contactNumber fields } catch (err) { setError("Failed to load contact info"); console.error(err); } finally { setIsLoading(false); } };
Step 3: Render the Contact Data
Update the target <div> to conditionally render the contact info based on state:
<div> {isLoading ? ( <span>Loading contact info...</span> ) : error ? ( <span className="text-danger">{error}</span> ) : ( <> <span>Contact Name : {contact?.name}</span> <span style={{ marginLeft: "1rem" }}>Contact Number : {contact?.contactNumber}</span> </> )} </div>
Full Modified Component Code
Here's the complete updated HomePage component:
import React, { useState, useEffect } from "react"; import ReactTable from "../_components/ReactTable/ReactTable"; import { Container, Row, Col } from "reactstrap"; import GlobalSearch from "../_components/ReactTable/GlobalSearch"; import axios from "axios"; import DefaultColumnFilter from "../_components/ReactTable/DefaultFilter"; const HomePage = () => { const [data, setData] = useState([]); const [filteredData, setFilteredData] = useState([]); // New state for contact data const [contact, setContact] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const columns = React.useMemo(() => [ { Header: "Reference", accessor: "reference", sortable: true }, { Header: "Name", accessor: "name", sortable: true } ], []); const getData = async () => { try { const result = await axios.get("api/contact"); setContact(result.data); } catch (err) { setError("Failed to load contact info"); console.error(err); } finally { setIsLoading(false); } }; const handleData = async () => { const resp = await axios.get("api/city"); const data = await resp.data.content; setData(data); setFilteredData(data); }; useEffect(() => { handleData(); getData(); }, []); const defaultColumn = React.useMemo( () => ({ Filter: DefaultColumnFilter }), [] ); const globalSearch = filteredDataOp => { setFilteredData(filteredDataOp); }; return ( <Container className="App"> <h2>Contact overview</h2> <hr /> {/* Updated contact display div */} <div> {isLoading ? ( <span>Loading contact info...</span> ) : error ? ( <span className="text-danger">{error}</span> ) : ( <> <span>Contact Name : {contact?.name}</span> <span style={{ marginLeft: "1rem" }}>Contact Number : {contact?.contactNumber}</span> </> )} </div> <div className="header-grid"> <h3>City :</h3> </div> <GlobalSearch data={data} filteredData={filteredData} handleDataArray={globalSearch} /> <hr /> <Row> <Col md={12} xs={12}> <ReactTable columns={columns} data={filteredData} defaultColumn={defaultColumn} showPagination={true} defaultPageSize={5} /> </Col> </Row> </Container> ); }; export default HomePage;
Key Notes
- Adjust
contact?.nameandcontact?.contactNumberto match the actual field names returned by your/api/contactendpoint. - The optional chaining operator (
?.) prevents errors if the contact data is undefined or missing fields. - Loading and error states ensure users get clear feedback if the API call takes time or fails.
内容的提问来源于stack exchange,提问作者Greg-A
相关产品推荐
相关产品推荐

