表格打印在控制台上,但不打印在屏幕上

问题描述 投票:0回答:1

我已经创建了一个机器学习模型,并且正在开发一个带有 Flask 后端的 React 应用程序。我正在将 API 数据从后端传递到前端。虽然没有错误,但表格没有显示在屏幕上。

下面是我的反应文件:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [tables, setTables] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('http://localhost:5000/api/tables');
        console.log('API response:', response.data);
        setTables(response.data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  // useEffect(() => {
  //   if (tables) {
  //     console.log('Tables state updated:', tables);
  //   }
  // }, [tables]);

  if (!tables) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>Agricultural Data</h1>

      {tables.final_table && tables.final_table.length > 0 ? (
        <div>
          <h2>Table 1: Max and Min Production</h2>
          <table>
            <thead>
              <tr>
                <th>Year</th>
                <th>Crop With Max Production</th>
                <th>Crop With Min Production</th>
              </tr>
            </thead>
            <tbody>
              {tables.final_table.map((row, index) => (
                <tr key={index}>
                  <td>{row.Year}</td>
                  <td>{row.CropWithMaxProd}</td>
                  <td>{row.CropWithMinProd}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <p>No data available for Table 1</p>
      )}

      {tables.final_table2 && tables.final_table2.length > 0 ? (
        <div>
          <h2>Table 2: Average Yield and Cultivation Area</h2>
          <table>
            <thead>
              <tr>
                <th>Crop Name</th>
                <th>Average Yield (Kg/Ha)</th>
                <th>Average Cultivation Area (Ha)</th>
              </tr>
            </thead>
            <tbody>
              {tables.final_table2.map((row, index) => (
                <tr key={index}>
                  <td>{row['Crop Name']}</td>  {/* Use dot notation */}
                  <td>{row['Average Yield (Kg/Ha)']}</td>
                  <td>{row['Average Cultivation Area (Ha)']}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <p>No data available for Table 2</p>
      )}
    </div>
  );
}

export default App;

下面是我的烧瓶文件

from flask import Flask, jsonify
from flask_cors import CORS
import pandas as pd

app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}})

@app.route('/api/tables')
def get_tables():
    # Load the data
    data = pd.read_csv("E:/MyApps/CropData/flask-server/Dataset/ManufacIndiaAgroDataset.csv")
    
    # Data cleaning and processing
    data['Crop Production (UOM:t(Tonnes))'] = data['Crop Production (UOM:t(Tonnes))'].fillna(0)
    data['Yield Of Crops (UOM:Kg/Ha(KilogramperHectare))'] = data['Yield Of Crops (UOM:Kg/Ha(KilogramperHectare))'].fillna(0)
    data['Area Under Cultivation (UOM:Ha(Hectares))'] = data['Area Under Cultivation (UOM:Ha(Hectares))'].fillna(0)
    
    # Group data by year and find max and min production crops
    year_group = data.groupby('Year')[['Crop Production (UOM:t(Tonnes))']].agg(['max', 'min']).reset_index()
    year_group.columns = ['Year', 'MaxProd', 'MinProd']
    
    # Merge with original data to get crop names
    merged_max = pd.merge(year_group, data, left_on=['Year', 'MaxProd'], right_on=['Year', 'Crop Production (UOM:t(Tonnes))'])
    merged_min = pd.merge(year_group, data, left_on=['Year', 'MinProd'], right_on=['Year', 'Crop Production (UOM:t(Tonnes))'])
    
    final_table = pd.DataFrame({
        'Year': merged_max['Year'],
        'CropWithMaxProd': merged_max['Crop Name'],
        'CropWithMinProd': merged_min['Crop Name']
    })
    
    # Calculating the average value and rounding off for 3 digits
    average_yield = data.groupby('Crop Name')['Yield Of Crops (UOM:Kg/Ha(KilogramperHectare))'].mean().round(3)
    average_cultivation_area = data.groupby('Crop Name')['Area Under Cultivation (UOM:Ha(Hectares))'].mean().round(3)
    
    final_table2 = pd.DataFrame({
        'Crop Name': average_yield.index,
        'Average Yield (Kg/Ha)': average_yield.values,
        'Average Cultivation Area (Ha)': average_cultivation_area.values
    })
    
    # Prepare the JSON response
    response = {
        "final_table": final_table.to_dict(orient="records"),
        "final_table2": final_table2.to_dict(orient="records")
    }

    # Debugging prints
    print("Final Table 1:", final_table)
    print("Final Table 2:", final_table2)
    print("Resulting data structure:", response)

    # Return the JSON response
    return jsonify(response)

if __name__ == '__main__':
    app.run(debug=True)

以下是输出图像:

https://i.sstatic.net/oTtXlvHA.png)]

(https://i.sstatic.net/DiGike4E.png)]

(https://i.sstatic.net/9yBajcKN.png)

如何使表格在屏幕上可见?

javascript reactjs flask axios flask-cors
1个回答
0
投票

final_table2
的屏幕截图中,前面的行似乎以
]}
结尾,但如果它是格式良好的 JSON 文件的一部分,则应以
]},
结尾,并带有逗号。如果您收到不带逗号的响应,它将被记录到控制台,但不会被正确解析,因此
tables
JS 变量将保持为空。

© www.soinside.com 2019 - 2024. All rights reserved.