如何获取JSON信息并将其提供给React组件?



获取请求(来自Google Sheets)返回stats,这是一个数组的数组。在stats中是一个球队的胜败列表(其中一个看起来像['Cannons', '4', '2'],就像你在teams中看到的那样)。我想让stats自动填充我的teams数组,或者把它给Table中的data道具。谢谢你的帮助!

const getSheetValues = async () => {
const request = await fetch(`https://sheets.googleapis.com/v4/spreadsheets/${SHEET_ID}/values/A1:C7`,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${ACCESS_TOKEN}`
}
});
const stats = await request.json();
console.log(stats);
return stats;
}
const teams = [
{
team: 'Cannons',
wins: 4,
loss: 2
},
{
team: 'Rhythm',
wins: 1,
loss: 5
}
]

const Standings = () => {
return (
<div className='cont'>
<div className='standings'>
<Table columns={columns} data={teams} className='tbl' />
</div>
</div>
)
}

我认为您的代码仍然是一个想法。但是没问题,我们就这么做吧。

在这里,我们将使用NextJS从Google Sheet获取数据,并通过API端点将结果传递给客户端。请记住,在中显示ACCESS_TOKEN是一个坏主意。公开。所以千万不要输入ACCESS_TOKEN在您的客户端应用程序。

服务器端

您可以通过以下两种方式从googleapi获取信息:

# /api/spreadsheets/[id].js
export default async function handler(req, res) {
const { id } = req.query;
const ACCESS_TOKEN = "yaXX.A0XXXXXXXXXX0-UsdRJ3DmO_sOrM-gexCZXXXXXXXXXX9bQ-VpOF_nETNoT-yWgIaj4LgJi5NIdoXXXXXXXXXXqiE0XYuOlVvIpXD3cw_fQDhXXXXXXXXXXP9Gs-VVjHnKXXXXXXXXXX7249iEHJ2-2x8PiXXXXXXXXXXBVEFTQVRBU0ZRRTY1ZHI4MGXXXXXXXXXXYURwYUdOTjh5Z0NrQQ0163";
const spreadsheet = await fetch(
`https://sheets.googleapis.com/v4/spreadsheets/${id}/values/A1:C7`,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${ACCESS_TOKEN}`,
},
}
);
const response = await spreadsheet.json();
res.status(200).json(response.values);
}

# /api/spreadsheets/[id].js
import { google } from "googleapis";
const CLIENT_ID = "840XXXXXXXXX-o5md8ddhsXXXXXXXXXi9fhu40v5n2XX2.apps.googleusercontent.com";
const CLIENT_SECRET = "GOCSPX-XXXXXX_-1-heXXXXXXAzW_7mr_1_";
const REDIRECT_URI = "https://developers.google.com/oauthplayground";
export default async function handler(req, res) {
const { id } = req.query;
const oauth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
REDIRECT_URI
);
oauth2Client.setCredentials({
refresh_token: "1//0XXXXXXXXXKS_CgYIXXXXXXXXXXF-L9Ir_MTdXXXXXXZ1V9-ZlBFXXXXdz3ywAV9XXXXXXXXXXMr6Jm9O8mvLeLXXXX8iaPSVKAc",
});
const sheets = google.sheets("v4");
const spreadsheets = await sheets.spreadsheets.get({
spreadsheetId: id,
auth: oauth2Client,
includeGridData: true,
});
const datas = spreadsheets.data.sheets[0].data[0].rowData.map((row) => {
return row.values.map((value) => value.formattedValue);
});
res.status(200).json(datas);
}

,两种方法的响应将是相同的:

[
[ 'Teams', 'Wins', 'Loss' ],
[ 'Cannons', '4', '2' ],
[ 'Racers', '6', '0' ]
]

,但请记住,当ACCESS_TOKEN是过期的。所以,请使用最后一个。您可以在这里阅读如何获取REFRESH_TOKEN.

接下来,在客户端。这里我们使用表组件呈现数据。

import { useEffect, useState } from "react";
import { Table } from "antd";
export default function Home() {
const [columns, setColumns] = useState();
const [data, setData] = useState();
useEffect(() => {
fetch("api/spreadsheets/1G8XS3aseeaIqEURr1Bt0rvogBb-hgqvAglw83b5qxSA")
.then((res) => res.json())
.then(
(response) => {
const columnNames = response.shift();
setColumns(
columnNames.map((name) => {
// to follow antd column properties
return {
title: name,
dataIndex: name.toLowerCase(),
key: name.toLowerCase(),
};
})
);
setData(
response.map((row, i) => {
// to follow antd dataSource properties
return columnNames.reduce((a, v, j) => {
a.key = `${i + 1}`;
a[v.toLowerCase()] = row[j];
return a;
}, {});
})
);
},
(error) => {
console.log(error);
}
);
}, []);
return (
<div>
<div>App</div>
<Table dataSource={data} columns={columns} />
</div>
);
}

相关内容

  • 没有找到相关文章

最新更新