首页 > 解决方案 > 如何在 React 中将 JSON 数据映射为表格

问题描述

我试图在获取数据后显示数据,但这不起作用:

import React, { Component } from "react";
import { Table, Button, ButtonToolbar } from "react-bootstrap";

const URL = "http://localhost:51644/api/";
let passedAthleteId = 0;
let passedAthleteSessionId = 0;

class AthleteTrainingSession extends Component {
  constructor(props) {
    super(props);
    this.state = {
      athleteTrainingSession: [],
      discussions: [],
      warmups: [],
      workouts: [],
      stretchings: [],
    };
  }

  componentDidMount() {
    this.fetchAthleteTrainingSession();
  }

  componentDidUpdate() {
    this.fetchAthleteTrainingSession();
  }

  fetchAthleteTrainingSession = () => {
    fetch(URL + `Coaches/4/Athletes/1/AthleteSessions/4`)
      .then((response) => response.json())
      .then((data) => {
        this.setState({
          athleteTrainingSession: data,
        });
      });
  };

  render() {
    const {
      athleteTrainingSession,
      discussions,
      warmups,
      workouts,
      stretchings,
    } = this.state;

    passedAthleteId = this.props.match.params.athleteId;
    passedAthleteSessionId = this.props.match.params.athleteSessionId;
    this.discussions = this.state.athleteTrainingSession.Discussions;
    this.warmups = this.state.athleteTrainingSession.Warmups;
    this.workouts = this.state.athleteTrainingSession.Workouts;
    this.stretchings = this.state.athleteTrainingSession.Stretchings;
    console.log(athleteTrainingSession);
    console.log(this.warmups);

    return (
      <React.Fragment>
        <div>
          <h2 className="mt-2">
            Programme d'entraînement :{" "}
            {athleteTrainingSession.TrainingProgramName}
          </h2>
          <h4>
            Séance d'entraînement : {athleteTrainingSession.TrainingSessionName}
          </h4>
        </div>
        <div>
          <ButtonToolbar>
            <Button variant="primary">Ajouter</Button>
            <Button variant="secondary">Discussion</Button>
          </ButtonToolbar>
          <h4>Échauffement</h4>
          <Table className="mt-4" striped bordered hover size="sm">
            <thead>
              <tr className="d-flex">
                <th className="col-6">Exercice</th>
                <th className="col-6">Options</th>
              </tr>
            </thead>
            <tbody>
              {warmups.map((warm) => (
                <tr className="d-flex" key={warm}>
                  <td className="col-6">{warm.ExerciseName}</td>
                  <td className="col-6">
                    <ButtonToolbar>
                      <Button className="mr-2" variant="info">
                        Modifier
                      </Button>
                      <Button className="mr-2" variant="danger">
                        Supprimer
                      </Button>
                    </ButtonToolbar>
                  </td>
                </tr>
              ))}
            </tbody>
          </Table>
        </div>
      </React.Fragment>
    );
  }
}

export default AthleteTrainingSession;

运动员训练会话包含获取的数据,热身是运动员训练会话的子对象。当我 console.log(warmups) 时,我可以看到它确实包含数据,但我无法在表格中显示它。

运动员训练会话包含获取的数据,热身是运动员训练会话的子对象。当我 console.log(warmups) 时,我可以看到它确实包含数据,但我无法在表格中显示它。

标签: reactjsfetch

解决方案


我认为您对在组件中使用状态有误解。您可以控制台,warmups因为在您的代码中console.log(this.warmups),您可以使用this.state.warmups

您应该 setState 从 fetch 获得的所有数据,即:

  fetchAthleteTrainingSession = () => {
    fetch(URL + `Coaches/4/Athletes/1/AthleteSessions/4`)
      .then((response) => response.json())
      .then((data) => {
        this.setState({
          athleteTrainingSession: data,
          warmups: data.Warmups,
          workouts: data.Workouts,
          discussions: data.Discussions,
          stretchings: data.Stretchings,
        });
      });
  };

通过这样做,现在您可以访问warmups数据this.state.warmups然后渲染它

render() {
  const {
    athleteTrainingSession,
    discussions,
    warmups,
    workouts,
    stretchings,
  } = this.state;

  return (
    <React.Fragment>
      ...
      {warmups.map((warm) => (
        <tr className="d-flex" key={warm}>
          <td className="col-6">{warm.ExerciseName}</td>
          <td className="col-6">
            <ButtonToolbar>
              <Button className="mr-2" variant="info">
                Modifier
              </Button>
              <Button className="mr-2" variant="danger">
                Supprimer
              </Button>
            </ButtonToolbar>
          </td>
        </tr>
      ))}
      ...
    </React.Fragment>
  )
}

推荐阅读