我想在此代码中显示提取的API

时间:2018-07-05 09:43:30

标签: javascript reactjs

我想将json数据呈现到表中,但是代码似乎无法呈现我的数据。这是我到目前为止尝试过的。

如何将数据呈现到表中?

import React, { Component } from "react";
import Reactable from "reactable";

var Table = Reactable.Table;
var Thead = Reactable.Thead;
var Th = Reactable.Th;

export class Users extends Component {
  constructor(props) {
    super(props);

    this.state = {
      pgNo: 0
    };
    var self = this;

    setTimeout(function() {
      self.setState({
        pgNo: self.state.pgNo + 1
      });
    }, 3000);
  }
  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/users", {
      method: "POST",
      body: JSON.stringify(Users),
      headers: {
        "Content-Type": "application/json"
      },
      credentials: "same-origin"
    }).then(response => response.json());
  }

  renderTable() {
    return (
      <Table
        className="table"
        style={style}
        filterable={["id", "display_name", "username", "email", "address"]}
        noDataText="No matching records found"
        itemsPerPage={5}
        currentPage={this.state.pgNo}
        sortable={true}
        data={this.state.Users}
      >
        <Thead>
          <Th column="id">ID</Th>
          <Th column="display_name">Name</Th>
          <Th column="username">Username</Th>
          <Th column="email">Location</Th>
          <Th column="address">Occupation</Th>
        </Thead>
      </Table>
    );
  }

  render() {
    return <div>{this.renderTable()}</div>;
  }
}

const style = {
  marginLeft: "18%",
  marginRight: "5%"
};

2 个答案:

答案 0 :(得分:0)

您在提取时进行了API调用,但未将响应数据存储在state中。

将您在构造函数中的状态定义为空错误,以避免破坏

fetch('https://jsonplaceholder.typicode.com/users', {
              method: "GET",
              headers: {
                  "Content-Type": "application/json"
              }})
              .then(response => response.json())
              .then(res=>this.setState({Users:res.users}))

答案 1 :(得分:0)

如果只想获取数据,则可以执行常规的fetch而没有其他选择,请解析json响应,并将结果设置为您的users

示例

export class Users extends Component {
  state = {
    pgNo: 0,
    users: []
  };

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => response.json())
      .then(res => {
        this.setState({
          users: res
        });
      });
  }

  render() {
    return (
      <Table
        className="table"
        style={{
          marginLeft: "18%",
          marginRight: "5%"
        }}
        filterable={["id", "display_name", "username", "email", "address"]}
        noDataText="No matching records found"
        itemsPerPage={5}
        currentPage={this.state.pgNo}
        sortable={true}
        data={this.state.users}
      >
        <Thead>
          <Th column="id">ID</Th>
          <Th column="display_name">Name</Th>
          <Th column="username">Username</Th>
          <Th column="email">Location</Th>
          <Th column="address">Occupation</Th>
        </Thead>
      </Table>
    );
  }
}