微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在React Bootstrap表中呈现axios响应

如何解决在React Bootstrap表中呈现axios响应

对不起,我知道这是一个新手问题,但我希望有人可以提供帮助。

我正在学习React,并且有一个todos-list.component.js组件,它显示axios请求的结果并在表中呈现,并且一切都很好(除了一些我目前不大为关注的样式问题):

import React,{ Component } from "react";
import { Link } from "react-router-dom";
import axios from "axios";

const Todo = (props) => (
  <tr>
    <td className={props.todo.todo_completed ? "completed" : ""}>
      {props.todo.todo_description}
    </td>
    <td className={props.todo.todo_completed ? "completed" : ""}>
      {props.todo.todo_responsible}
    </td>
    <td className={props.todo.todo_completed ? "completed" : ""}>
      {props.todo.todo_priority}
    </td>
    <td className={props.todo.todo_completed ? "completed" : ""}>
      {props.todo.todo_cardnumber}
    </td>
    <td className={props.todo.todo_completed ? "completed" : ""}>
      {props.todo.todo_playername}
    </td>
    <td className={props.todo.todo_completed ? "completed" : ""}>
      {props.todo.todo_teamname}
    </td>
    <td>
      <Link to={"/edit/" + props.todo._id}>Edit</Link>
    </td>
  </tr>
);

export default class TodosList extends Component {
  constructor(props) {
    super(props);
    this.state = { todos: [] };
  }

  componentDidMount() {
    axios
      .get(
        "https://webhooks.mongodb-realm.com/api/client/v2.0/app/todo-psiro/service/Todo/incoming_webhook/todos"
      )
      .then((response) => {
        this.setState({ todos: response.data });
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  componentDidUpdate() {
    axios
      .get(
        "https://webhooks.mongodb-realm.com/api/client/v2.0/app/todo-psiro/service/Todo/incoming_webhook/todos"
      )
      .then((response) => {
        this.setState({ todos: response.data });
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  todoList() {
    return this.state.todos.map(function (currentTodo,i) {
      return <Todo todo={currentTodo} key={i} />;
    });
  }

  render() {
    return (
      <div>
        <h3>Todos List</h3>
        <table className="table table-striped" style={{ marginTop: 20 }}>
          <thead>
            <tr>
              <th>Description</th>
              <th>Team Name</th>
              <th>Player Name</th>
              <th>Card Number</th>
              <th>Responsible</th>
              <th>Priority</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>{this.todoList()}</tbody>
        </table>
      </div>
    );
  }
}

然后我有一个不同的组件table.component.js,它将静态数据呈现到React Bootstrap表(https://react-bootstrap-table.github.io/react-bootstrap-table2/)中,再次可以正常工作:

import BootstrapTable from "react-bootstrap-table-next";
import paginationFactory from "react-bootstrap-table2-paginator";
import React,{ Component } from "react";
import { Link } from "react-router-dom";
import axios from "axios";

const data = [
  {
    id: 0,name: "banana",price: "0.25",},{
    id: 1,name: "spinach",price: "4.49",{
    id: 2,name: "icecream",price: "4.99",{
    id: 3,name: "bagel",price: "1.19",{
    id: 4,name: "fish",price: "10.00",];

const columns = [
  {
    datafield: "id",hidden: true,{
    datafield: "name",text: "Grocery",sort: true,{
    datafield: "price",text: "Price",formatter: (cell,row) => {
      return <p>${cell}</p>;
    },sortFunc: (a,b,order,datafield,rowA,rowB) => {
      const numA = parseFloat(a);
      const numB = parseFloat(b);
      if (order === "asc") {
        return numB - numA;
      }
      return numA - numB; // desc
    },];

const BasicTable = () => {
  return (
    <BootstrapTable
      keyField="id"
      data={data}
      columns={columns}
      striped
      hover
      condensed
      pagination={paginationFactory({})}
    />
  );
};

export default BasicTable;

不过,我想做的就是将这些结合起来,以便axios GET请求的结果通过React Bootstrap表呈现。有人可以帮忙吗?

解决方法

  1. apiCall放在您的componentDidMount中
  2. 仅在数据到达时显示表格。
  3. 将您的todo对象的键映射到列中的dataField。

您可以查看工作示例here

import BootstrapTable from "react-bootstrap-table-next";
import paginationFactory from "react-bootstrap-table2-paginator";
import React,{ Component } from "react";
import { Link } from "react-router-dom";
import axios from "axios";


const columns = [
  {
    dataField: "todo_id",text: "id",},{
    dataField: "todo_description",text: "description",sort: true,{
    dataField: "todo_priority",text: "priority",];

const url = 'https://webhooks.mongodb-realm.com/api/client/v2.0/app/todo-psiro/service/ToDo/incoming_webhook/todos'

class BasicTable extends React.Component {
  state = { data: null };

  async componentDidMount() {
    const { data } = await axios.get(url)
    this.setState({ data });
  }

  render() {
    if (!this.state.data) return null;
    console.log(this.state.data);
    
    return (
      <BootstrapTable
        keyField="id"
        data={this.state.data}
        columns={columns}
        striped
        hover
        condensed
        // pagination={paginationFactory({})}
      />
    ) 
  }
}


export default BasicTable;
,

我建议使用功能组件,因为React ecysystem正在朝着这种方法发展。

您可以使用useState钩子来管理状态,并使用useEffect钩子来进行API调用。

类似这样的东西:

import BootstrapTable from "react-bootstrap-table-next";
import paginationFactory from "react-bootstrap-table2-paginator";
import React,{
  useState,useEffect
} from "react";
import {
  Link
} from "react-router-dom";
import axios from "axios";

const columns = [{
    dataField: "_id",hidden: true
  },text: "Description",sort: true
  },{
    dataField: "todo_teamname",text: "Team Name",{
    dataField: "todo_playername",text: "Player Name",{
    dataField: "todo_cardnumber",text: "Card Number",{
    dataField: "todo_responsible",text: "Responsible",text: "Priority",{
    dataField: "action",text: "Action"
  }
];

const TableWithData = () => {
  const [data,setData] = useState([]);

  useEffect(() => {
    axios
      .get(
        "https://webhooks.mongodb-realm.com/api/client/v2.0/app/todo-psiro/service/ToDo/incoming_webhook/todos"
      )
      .then(response => {
        setData(response.data);
      })
      .catch(function(error) {
        console.log(error);
      });
  },[]);

  return ( <
    BootstrapTable keyField = "id"
    data = {
      data
    }
    columns = {
      columns
    }
    striped hover condensed pagination = {
      paginationFactory()
    }
    />
  );
};

export default TableWithData;

看看TableWithData组件。

以下是 Working Sample StackBlitz 供您参考。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。