如何通过react.js组件中的表显示JSON数据

时间:2019-03-21 09:03:48

标签: javascript reactjs axios

我试图在我的react组件中将从数据库检索的json数据显示为表。我正在使用axios来发布快递服务器中的数据并从中获取数据。 这是我的反应成分。

import React from "react";
// @material-ui/core components
import withStyles from "@material-ui/core/styles/withStyles";
// core components
import GridItem from "components/Grid/GridItem.jsx";
import GridContainer from "components/Grid/GridContainer.jsx";
import Table from "components/Table/Table.jsx";
import Card from "components/Card/Card.jsx";
import CardHeader from "components/Card/CardHeader.jsx";
import CardBody from "components/Card/CardBody.jsx";

import Button from "components/CustomButtons/Button.jsx";
import CardFooter from "components/Card/CardFooter.jsx";

import axios from "axios";

const styles = {
  cardCategoryWhite: {
    "&,& a,& a:hover,& a:focus": {
      color: "rgba(255,255,255,.62)",
      margin: "0",
      fontSize: "14px",
      marginTop: "0",
      marginBottom: "0"
    },
    "& a,& a:hover,& a:focus": {
      color: "#FFFFFF"
    }
  },
  cardTitleWhite: {
    color: "#FFFFFF",
    marginTop: "0px",
    minHeight: "auto",
    fontWeight: "300",
    fontFamily: "'Roboto', 'Helvetica', 'Arial', sans-serif",
    marginBottom: "3px",
    textDecoration: "none",
    "& small": {
      color: "#777",
      fontSize: "65%",
      fontWeight: "400",
      lineHeight: "1"
    }
  }
};


function createUser() {
  axios.post("http://172.104.189.215:4000/users").then(response => {console.log(response)}).catch(error => {console.log(error.response)});
}

function TableList(props) {


  axios.get("http://172.104.189.215:4000/readUsers").then(json => console.log(json)).catch(err => console.log(err));;


  return (
    <GridContainer>
      <GridItem xs={12} sm={12} md={12}>
        <Button color="primary" onClick={createUser}>Create User</Button>
        <Card>
          <CardHeader color="primary">
            <h4 className={classes.cardTitleWhite}>User List</h4>
            <p className={classes.cardCategoryWhite}>
              {/*Here is a subtitle for this table*/}
            </p>
          </CardHeader>
          <CardBody>
            <Table
              tableHeaderColor="primary"
              tableHead={["Name", "Country", "City", "Salary"]}
              tableData={[
                ["Dakota Rice", "Niger", "Oud-Turnhout", "$36,738"],
                ["Minerva Hooper", "Curaçao", "Sinaai-Waas", "$23,789"],
                ["Sage Rodriguez", "Netherlands", "Baileux", "$56,142"],
                ["Philip Chaney", "Korea, South", "Overland Park", "$38,735"],
                ["Doris Greene", "Malawi", "Feldkirchen in Kärnten", "$63,542"],
                ["Mason Porter", "Chile", "Gloucester", "$78,615"],
                ["LALA", "NOOB", "LOL", "$12345"]
              ]}
            />
          </CardBody>
          <CardFooter>
            <Button color="primary">Update Profile</Button>
          </CardFooter>
        </Card>
      </GridItem>
    </GridContainer>
  );
}

export default withStyles(styles)(TableList);

我成功地从数据库中检索了数据并显示在控制台中。但是,我不知道如何通过表格显示它。有人在这个问题上有好的解决方案吗?

3 个答案:

答案 0 :(得分:1)

更好的方法是为表创建一个单独的组件,以显示您从后端接收的数据。 否则,您可以通过以下方式进行少量更改以使用同一组件:

        class TableList extends React.Component {
          constructor() {
            super();
            this.state = {
              users: []
            };
          }
          
          function createUser() {
            axios.post("http://172.104.189.215:4000/users").then(response => { 
              console.log(response)}).catch(error => {console.log(error.response)});
            });
          }
          componentDidMount() {
            axios.get("https://pokeapi.co/api/v2/pokemon/ditto/")
              .then(json => {
                this.setState({users: json});
                console.log({json})
              });
              .catch(err => console.log(err));;
          }
          render() {
            const {users} = this.state;
            console.log({users})
            // your table
            return (
              <GridContainer>
                <GridItem xs={12} sm={12} md={12}>
                  <Button color="primary" onClick={createUser}>Create User</Button>
                  <Card>
                    <CardHeader color="primary">
                      <h4 className={classes.cardTitleWhite}>User List</h4>
                      <p className={classes.cardCategoryWhite}>
                        {/*Here is a subtitle for this table*/}
                      </p>
                    </CardHeader>
                    <CardBody>
                      <Table
                        tableHeaderColor="primary"
                        tableHead={["Name", "Country", "City", "Salary"]}
                        tableData={users}
                      />
                    </CardBody>
                    <CardFooter>
                      <Button color="primary">Update Profile</Button>
                    </CardFooter>
                  </Card>
                </GridItem>
              </GridContainer>
            );
          }
        }

        const styles = {
          cardCategoryWhite: {
            "&,& a,& a:hover,& a:focus": {
              color: "rgba(255,255,255,.62)",
              margin: "0",
              fontSize: "14px",
              marginTop: "0",
              marginBottom: "0"
            },
            "& a,& a:hover,& a:focus": {
              color: "#FFFFFF"
            }
          },
          cardTitleWhite: {
            color: "#FFFFFF",
            marginTop: "0px",
            minHeight: "auto",
            fontWeight: "300",
            fontFamily: "'Roboto', 'Helvetica', 'Arial', sans-serif",
            marginBottom: "3px",
            textDecoration: "none",
            "& small": {
              color: "#777",
              fontSize: "65%",
              fontWeight: "400",
              lineHeight: "1"
            }
          }
        };

答案 1 :(得分:0)

这篇文章有几点要点。恕我直言,您似乎已经硬编码了表格的数据。这样行吗?您的表“真的”期望包含一个数组的对象,然后该数组包含一个列数据的数组吗?

正如lankovova所说,我们需要查看表组件以了解如何处理传递到该组件中的数据。

您应该在这里重新访问数据结构,因为您通常希望使用一个JSON对象数组,而不是示例中的数组。

就目前而言,API响应数据将永远不会出现在表中,因为您对数据所做的唯一操作就是将其记录到控制台中,或者这是您的关键问题?

答案 2 :(得分:0)

当您从API获取数据用户时,请将其设置为状态用户。组件TableList填充来自状态用户的数据。因此TableList应该作为类Component编写。

class TableList extends React.Component {
  constructor() {
    super();
    this.state = {
      users: []
    };
  }
  componentDidMount() {
    axios.get("https://pokeapi.co/api/v2/pokemon/ditto/")
      .then(json => {
        this.setState({users: json});
        console.log({json})
      })
      .catch(err => console.log(err));;
  }
  render() {
    const {users} = this.state;
    console.log({users})
    // your table
  }
}