反应:React表未呈现多个不同状态变量的数据

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

我正在使用此react-table component library。我有一个带有三个状态变量的data状态变量,并且正在进行三个API调用以获取所有这三个变量的数据。然后,在JSX中,我要分解response.data并将其传递到datareact-table component内部。但是,它不起作用。

我的react-table组件的代码:

import React, { Component } from "react";
// react component for creating dynamic tables
import ReactTable from "react-table";

import axios from "axios";
import {
  Card,
  CardBody,
  CardHeader,
  CardTitle,
  Row,
  Col,
  Dropdown,
  DropdownToggle,
  DropdownMenu,
  DropdownItem,
} from "reactstrap";

class DataViewTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {
        system: [],
        measurements: [],
        measurementData: [],
      },
      isLoading: false,
      dropdownOpen: false,
    };
  }

  signal = axios.CancelToken.source();

  componentDidMount() {
    this.handleGetSystemInfo();
    this.handleGetMeasurementsInfo();
    this.handleGetMeasurementDataInfo();
    this.addFilterPlaceholder();
  }

  componentUnMount() {
    this.signal.cancel("Api is being canceled");
  }
  handleGetSystemInfo = async () => {
    this.setState({ isLoading: true });
    await axios
      .get("http://www.mocky.io/v2/5ed488f83300005f00f7a20e")
      .then((response) => {
        // handle success
        console.log("system:", response.data);
        this.setState({ system: response.data });
      })
      .catch((error) => {
        // handle error
        if (axios.isCancel(error)) {
          console.log("Unable to fetch system data", error.message);
        } else {
          this.setState({ isLoading: false });
        }
      });
  };
  handleGetMeasurementsInfo = async () => {
    this.setState({ isLoading: true });
    await axios
      .get("http://www.mocky.io/v2/5ed4899d3300003f00f7a212")
      .then((response) => {
        // handle success
        console.log("measurements:", response.data);
        this.setState({ measurements: response.data });
      })
      .catch((error) => {
        // handle error
        if (axios.isCancel(error)) {
          console.log("Unable to fetch measurements info", error.message);
        } else {
          this.setState({ isLoading: false });
        }
      });
  };
  handleGetMeasurementDataInfo = async () => {
    this.setState({ isLoading: true });
    await axios
      .get("http://www.mocky.io/v2/5ed48a113300007900f7a213")
      .then((response) => {
        // handle success
        console.log("measurement data:", response.data);
        this.setState({ measurementData: response.data });
      })
      .catch((error) => {
        // handle error
        if (axios.isCancel(error)) {
          console.log("Unable to fetch measurementData", error.message);
        } else {
          this.setState({ isLoading: false });
        }
      });
  };

  addFilterPlaceholder = () => {
    const filters = document.querySelectorAll("div.rt-th > input");
    for (let filter of filters) {
      filter.placeholder = "Search..";
    }
  };

  toggleDropdown = () => {
    this.setState((state) => {
      return {
        dropdownOpen: !state.dropdownOpen,
      };
    });
  };

  render() {
    const { dropdownOpen } = this.state;
    const { system, measurementData, measurements } = this.state.data;
    return (
      <>
        <div className="content">
          <Row className="mt-5">
            <Col xs={12} md={12}>
              <Card>
                <CardHeader>
                  <CardTitle tag="h4">Table of data</CardTitle>
                  <hr />
                  <Dropdown
                    isOpen={dropdownOpen}
                    toggle={this.toggleDropdown}
                    className="shipsDropdown"
                  >
                    <DropdownToggle caret>Ships</DropdownToggle>
                    <DropdownMenu>
                      <DropdownItem>Foo Action</DropdownItem>
                      <DropdownItem divider />
                      <DropdownItem>Bar Action</DropdownItem>
                      <DropdownItem divider />
                      <DropdownItem>Quo Action</DropdownItem>
                    </DropdownMenu>
                  </Dropdown>
                </CardHeader>
                <CardBody>
                  <ReactTable
                    data={(system, measurements, measurementData)}
                    filterable
                    resizable={false}
                    columns={[
                      {
                        Header: "System",
                        accessor: "name",
                      },
                      {
                        Header: "Measurement",
                        accessor: "name",
                      },
                      {
                        Header: "Value",
                        accessor: "values.temp1, values.temp2",
                      },
                      {
                        Header: "Min",
                        accessor: "",
                      },
                      {
                        Header: "Max",
                        accessor: "",
                      },
                      {
                        Header: "Avg",
                        accessor: "",
                      },
                      {
                        Header: "Last",
                        accessor: "",
                      },
                      {
                        Header: "Bar",
                        accessor: "",
                      },
                    ]}
                    showPaginationTop
                    showPaginationBottom={false}
                    className="-striped -highlight"
                  />
                </CardBody>
              </Card>
            </Col>
          </Row>
        </div>
      </>
    );
  }
}

export default DataViewTable;

Adding CodeSandbox link

reactjs destructuring react-table
1个回答
0
投票

这里有很多事情需要正确处理

  • 您已将状态直接设置为measurementData,度量和系统,而不是在axios请求中的数据之下,因此必须直接使用它们
 constructor(props) {
    super(props);
    this.state = {
        system: [],
        measurements: [],
        measurementData: [],
      ...
    };
  }
  • 您没有将cancelToken传递给axios请求。另外,单独调用必须使用单独的cancelToken
this.signalToken = axios.CancelToken.source();
await axios
      .get("http://www.mocky.io/v2/5ed48a113300007900f7a213", {
         cancelToken: this.signalToken.token
      })

对于其他请求,依此类推,然后取消请求,例如

this.signalToken.cancel();
this.measurementsToken.cancel()
this.measurementsDataToken.cancel()

  • ReactTable的数据应该是合并资源的数组,如果它们具有相同的格式。但是它们具有不同的格式,您应该考虑呈现多个ReactTables
<ReactTable
    data={[...system, ...measurements, ...measurementData]}
    filterable
    resizable={false}

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