首页 > 解决方案 > axios方法Get:我的表无法显示数据

问题描述

我想在我的网站上显示一个 JSON。我正在使用一个带有安全令牌的 API,一切都很好,直到我想在我的页面中显示 json 的数据,并且它只存在于我的控制台中,因为我可以在我的控制台中看到数据。我希望你能帮助我。

import React from 'react';
import axios from 'axios';

const Table = () => {

const url = 'someApi';
const token = 'someToken'   
axios(url, {
    method: 'get',
    headers: {
        'Authorization': `Bearer ${token}`
    },
    'body': JSON.stringify({
         name: this.state.name,
         quantity: this.state.quantity,
         price: this.state.price,
     })
})
// .then(response => response.json())
.then(response => {
    console.log(response);
})
.catch(error => console.error(error));

    return(
       <>
        <table>
            <thead>
                <tr>
                    <th>sku</th>
                    <th>name</th>
                    <th>quantity</th>
                    <th>price</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
       </>
    )
}

export default Table;

标签: javascriptjsonreactjsaxios

解决方案


我认为你应该更多地了解反应以及如何使用地图功能,我更喜欢在 youtube 上观看一些关于它的 tuts。

生病分享一些axios和映射数据的简单用法,希望对你有所帮助。

const Table = () => {

  const [data, setData] = React.useState(null);

  React.useEffect(() => {
    if (!data) {
      axios("https://jsonplaceholder.typicode.com/users", {
        method: "GET",
      })
        .then((res) => setData(res.data))
        .catch((error) => console.error(error));
    }
  },[data]);

  return (
    <table>
      <thead>
        <tr>
          <th>id</th>
          <th>name</th>
          <th>email</th>
          <th>phone</th>
        </tr>
      </thead>
      <tbody>
        {data
          ? data.map((d) => (
              <tr key={d.id}>
                <td>{d.id}</td>
                <td>{d.name}</td>
                <td>{d.email}</td>
                <td>{d.phone}</td>
              </tr>
            ))
          : null}
      </tbody>
    </table>
  );
}

ReactDOM.render(
  <Table />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<div id="react"></div>


推荐阅读