如何在React中通过GET API获取数据并以表格形式展示投诉信息?
Solution to Display Complaint Data with React-Bootstrap Table
Hey there! Looks like you're already halfway there since you can fetch the data successfully and display it as a list. Converting that to a table is straightforward—you just need to map over your complaints state data to populate the table body (<tbody>) with rows and cells. Here's how to do it:
Step-by-Step Fixes & Explanation
- Add the Table Body: You already have the
<thead>set up, now you need to add a<tbody>section where your data rows will live. - Map Over Complaint Data: Use
Array.map()onthis.state.complaintsto generate a<tr>for each complaint, with<td>elements corresponding to each table header. - Fix Constructor Issue: You shouldn't call
this.componentDidMount()directly inside the constructor—React will automatically run this lifecycle method when the component mounts, so remove that line.
Modified Working Code
import React, { Component } from 'react'; import { Table } from 'react-bootstrap'; import axios from 'axios'; export default class Display extends React.Component { constructor(props) { super(props); // Removed direct call to componentDidMount() - React handles this automatically this.state = { complaints: [] }; } componentDidMount() { axios.get(`http://localhost:80/get/complaints`) .then(res => { this.setState({ complaints: res.data }); }) .catch(err => { // Optional: Add error handling here console.error('Failed to fetch complaints:', err); }); } render() { return ( <Table responsive> <thead> <tr> <th>Regd_no</th> <th>Year Of Study</th> <th>Location</th> <th>Department</th> <th>Disciplinary Issue</th> </tr> </thead> {/* Table body with dynamic data rows */} <tbody> {this.state.complaints.map(complaint => ( <tr key={complaint.id}> <td>{complaint.Regdno}</td> <td>{complaint.YearOfStudy}</td> {/* Adjust field name to match your data */} <td>{complaint.Location}</td> {/* Adjust field name to match your data */} <td>{complaint.Department}</td> {/* Adjust field name to match your data */} <td>{complaint.DisciplinaryIssue}</td> {/* Adjust field name to match your data */} </tr> ))} </tbody> </Table> ); } }
Important Notes:
- Field Names: Make sure the property names in
<td>(likecomplaint.YearOfStudy) exactly match the keys present in your API response data. If your data uses different naming (e.g.,year_of_studyinstead ofYearOfStudy), update these to match. - Key Prop: Always include a unique
keyprop when mapping arrays in React—usingcomplaint.idis perfect here since it's a unique identifier from your database. - Error Handling: I added a
.catch()block to handle any potential API errors, which is a good practice to avoid silent failures.
That should get your table populated with all the complaint data! Test it out, and adjust the field names if needed to match your actual API response structure.
内容的提问来源于stack exchange,提问作者Tarun
相关产品推荐
相关产品推荐

