简体   繁体   English

如何使用react js在点击的基础上动态获取api数据

[英]how to fetch api data dynamically on the basis of click using react js

In react js how to fetch api data dynamically on the basis of click button.in my below code i want to fetch data on the basis of click using react js.how can we do that.在 react js 中,如何根据点击按钮动态获取 api 数据。在我下面的代码中,我想使用 react js 在点击的基础上获取数据。我们该怎么做。

https://mocki.io/v1/be3cb19b-bd49-4a82-b19b-44b859e19d5d my api is this.in my below code i make one table and i want when i click on row 1st that is airplane and when i click first row then fetch airplane data using this api https://mocki.io/v1/be3cb19b-bd49-4a82-b19b-44b859e19d5d . https://mocki.io/v1/be3cb19b-bd49-4a82-b19b-44b859e19d5d我的 api 是这个。在我下面的代码中,我制作一个表格,当我点击第一行时我想要第一行然后使用此 api https://mocki.io/v1/be3cb19b-bd49-4a82-b19b-44b859e19d5d获取飞机数据。

how can we do that.我们怎么能做到这一点。

is there any help.its very thankful.有什么帮助吗。非常感谢。

var TableComponent = React.createClass({
  render: function() {
    // Data
    var dataColumns = this.props.data.columns;
    var dataRows = this.props.data.rows;

    var tableHeaders = (<thead>
          <tr>
            {dataColumns.map(function(column) {
              return <th>{column}</th>; })}
          </tr>
      </thead>);

 var tableBody = dataRows.map(function(row) {
      return (
        <tr>
          {dataColumns.map(function(column) {
            return <td>{row[column]}</td>; })}
        </tr>); });
    // Decorate with Bootstrap CSS
    return (<table className="table table-bordered table-hover" width="100%">
        {tableHeaders}
        {tableBody}
      </table>) }});
        

// Example Data
var tableData = {
 columns: ['Service_Name', 'Cost/Unit'],
  rows: [{
    'Service_Name': 'airplane',
    'Cost/Unit': 50
   
  }, {
    'Service_Name': 'cat',
    'Cost/Unit': 50
  },{
    'Service_Name': 'fruits',
    'Cost/Unit': 50
  }, {
    'Service_Name': 'pool',
    'Cost/Unit': 50
  }]
};

ReactDOM.render(
  <TableComponent data = {tableData} />,
  document.getElementById('table-component'));

I hope it will help:我希望它会有所帮助:

const MyTable = ({data}) => {
  const fetchSomething = serviceName => fetch(`https://whatever?service_name=${serviceName}`).then(...);

  return (
    <Table>
      <tr>
        {data.columns.map(column => (<th key={column}>{column}</th>))}
      </tr>
      {data.rows.map((row, index) => (
        <tr key={index} onClick={fetchSomething(row['Service_Name'])}>
          <td>{row['Service_Name']}</td>
          <td>{row['Cost/Unit']}</td>
        </tr>
      ))}
    </Table>
    )
}

Probably you need something like this.可能你需要这样的东西。 Steps for implementation:实施步骤:

  1. Add a click listener on your row在您的行上添加一个点击监听器
  2. Implement handleRowClick function similar to the below implementation.实现与以下实现类似的 handleRowClick function。 Save all that you need from the response to the React state.从对 React state 的响应中保存您需要的所有内容。
  3. Show the result somewhere in UI, or just console.log it.在 UI 中的某处显示结果,或者只是 console.log 它。

Here is some code below that might help you下面是一些可能对您有所帮助的代码

class TableComponent extends React.Component {
  state = {};

  handleRowClick = async () => {
    // make an API call here, sth like
    const url = "https://mocki.io/v1/be3cb19b-bd49-4a82-b19b-44b859e19d5d";
    const response = await fetch(url);
    this.setState({
      ...response,
    });
  };

  render() {
    var dataColumns = this.props.data.columns;
    var dataRows = this.props.data.rows;

    var tableHeaders = (
      <thead>
        <tr>
          {" "}
          {dataColumns.map(function (column) {
            return <th> {column} </th>;
          })}{" "}
        </tr>{" "}
      </thead>
    );

    var tableBody = dataRows.map((row) => {
      return (
        <tr onClick={this.handleRowClick}>
          {" "}
          {dataColumns.map(function (column) {
            return (
              <td>
                {" "}
                <a target="_blank" rel="noopener noreferrer" href={row.url}>
                  {" "}
                  {row[column]}{" "}
                </a>
              </td>
            );
          })}{" "}
        </tr>
      );
    });

    // Decorate with Bootstrap CSS
    return (
      <table className="table table-bordered table-hover" width="100%">
        {" "}
        {tableHeaders} {tableBody}{" "}
      </table>
    );
  }
}

// Example Data
var tableData = {
  columns: ["Service_Name", "Cost/Unit", "Unit", "Units Requested"],
  rows: [
    {
      Service_Name: "airplane",
      "Cost/Unit": 50,
      Unit: "1 Hour",
      "Units Requested": 12,
      url:
        "http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blue.png",
    },
    {
      Service_Name: "cat",
      "Cost/Unit": 50,
      Unit: "1 Hour",
      "Units Requested": 12,
      url:
        "http://codeskulptor-assets.commondatastorage.googleapis.com/assets_clock_background.png",
    },
    {
      Service_Name: "fruits",
      "Cost/Unit": 50,
      Unit: "1 Hour",
      "Units Requested": 12,
      url:
        "http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blend.png",
    },
    {
      Service_Name: "pool",
      "Cost/Unit": 50,
      Unit: "1 Hour",
      "Units Requested": 12,
    },
  ],
};

ReactDOM.render(
  <TableComponent data={tableData} />,
  document.getElementById("table-component")
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM