react數據從本地讀取_如何將從Google表格讀取的React應用程序部署到Netlify

react數據從本地讀取

In this tutorial, we’re going to cover how to connect to a spreadsheet hosted on Google, display that information inside a React application, and deploy it to Netlify.

在本教程中,我們將介紹如何連接到Google托管的電子表格,如何在React應用程序中顯示該信息并將其部署到Netlify。

Skip to “The Setup” if you don’t care where the data will be coming from or why I chose to build this. I won’t be mad, I promise.

如果您不在乎數據將來自何處或為什么選擇構建它,則跳至“設置”。 我保證,我不會生氣。

Right now the final result looks like this, but I’ll be adding more features to it shortly.

現在,最終結果看起來像這樣,但是我很快會為其添加更多功能。

為什么 (The Why)

I love cars ? ??. If you’re even slightly interested in cars, you’ve probably at some point stumbled upon Doug Demuro’s Youtube channel. He reviews a wide range of cars anywhere from a $3 Million Ferrari Enzo to a 3 wheeled BMW Isetta. Doug’s format is a little bit different than most user reviews. His roughly 20 minute videos have three main points:

我愛汽車嗎? ? 如果您甚至對汽車不太感興趣,那么您可能會偶然發現Do ug Demuro的Youtube頻道。 他評論了各種各樣的汽車,包括價值300 萬美元的法拉利Enzo t oa 3 輪式BMW Isetta。 Doug的格式與大多數用戶評論略有不同。 他大約20分鐘的視頻有三個要點:

  • Interesting quirks and features: about 70% of the video is him taking about the car’s exterior and interior quirks. These can range from a paragraph in the owner’s manual to an interesting shape of the break lights.

    有趣的怪癖和功能:大約70%的視頻是他關于汽車外觀和內部怪癖的。 這些范圍可以從使用手冊中的段落到有趣的斷燈形狀。
  • Driving: about 20% of the video is Doug taking the car out on the road and making funny faces when he accelerates. He also talks about the interior noise, handling, speed, and so on.

    駕駛:大約有20%的視頻是道格將汽車駛出公路,并在他加速時做鬼臉。 他還談到了室內噪音,處理,速度等。
  • The DougScore: Doug created a spreadsheet with all the cars he’s ever reviewed (since creating the scoring system) and ranked all of them using his own system. It’s broken down into two categories:

    DougScore:Doug創建了一個電子表格,其中包含他曾經審查過的所有汽車(自創建計分系統以來),并使用自己的系統對所有汽車進行排名。 它分為兩類:

    * Weekend Score: Essentially how much fun the car is.

    *周末分數:從本質上講,這輛車有多有趣。

    * Daily Score: Essentially how practical the car is.

    *每日得分:從本質上講,汽車的實用性。

That’s why, in my opinion, he can get over 1.5M views on a 25 minute video of a minivan ???. Since the videos are so quirky, and Doug himself is pretty quirky too, his following has come up with some creative comments. My favourite are the “Doug is the type of guy to…” remarks, like those above.

我認為,這就是為什么他可以在25分鐘的微型貨車視頻中獲得超過150萬的觀看次數。 由于視頻是如此古怪,而且道格本人也很古怪,因此他的追隨者提出了一些富有創意的評論。 我最喜歡的是“道格是那種……”。

And now, to all of you who have stuck around after that intro that has nothing to do with building an app, Google Sheets API, or React, here’s what I am on about.

現在,對于所有在介紹之后一直停留在與構建應用程序,Google Sheets API或React無關的人來說,這就是我要做的。

設置 (The Setup)

Doug keeps his spreadsheet on Google Sheets, and anyone with a link can access it. To me, it was hard to navigate. So I decided to see if there was a way to extend it and add some additional functionality.

道格將電子表格保存在Google表格中,任何有鏈接的人都可以訪問它。 對我來說,這很難導航。 因此,我決定看看是否有擴展它并添加一些其他功能的方法。

React創建應用 (React Create App)

Facebook’s React boilerplate will get us started fairly quickly without the need to configure any backends. In your Terminal of choice (Hyper for me), go ahead and put in:

Facebook的React樣板將使我們相當快速地開始,而無需配置任何后端。 在您選擇的終端機(對我來說, 超級 )中,繼續輸入:

npx create-react-app doug-score
cd doug-score
yarn start

(Or npm start, whatever floats your boat but I'll be using yarn.)

(或者npm start ,無論您的船如何漂浮,但我將使用毛線。)

Open up the folder in your editor of choice (VS Code for me) and head over to App.js. We’re going to create a separate component called CarList , putting it inside a components folder and adding it to App .

在您選擇的編輯器(對我而言是VS Code)中打開文件夾,然后轉到App.js 我們將創建一個單獨的名為CarList組件,將其放在components文件夾中,并將其添加到App

import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import CarList from "./components/CarList";
class App extends Component {render() {return (<div className="App"><header className="App-header"><img src={logo} className="App-logo" alt="logo" /><h1 className="App-title">Welcome to React</h1></header><CarList /></div>);}
}
export default App;

For now, this is what CarList component will look like:

現在,這是CarList組件的外觀:

import React, { Component } from 'react';
class CarList extends Component {render() {return (<div>This will be the car list</div>);}
}

Google Sheets API (Google Sheets API)

Let’s go ahead and create a new project on Google. I’ve called it doug-score. Once it’s been created, in the APIs box, click “Go to APIs overview.” Once you click “Enable APIs and Services” you’ll be presented with the API Library. We’ll go ahead and search for “Google Sheets API.” Once you click into it, click “Enable,” and after it’s processed you should see this page.

讓我們繼續, 在Google上創建一個新項目 。 我稱它為doug-score 。 創建完成后,在“ API”框中,單擊“轉到API概述”。 單擊“啟用API和服務”后,您將看到API庫。 我們將繼續搜索“ Google Sheets API”。 單擊后,單擊“啟用”,處理完成后,您應該會看到此頁面。

In the sidebar, head over to “Credentials,” click the “Create credentials” button, and select “API Key.” Click the “Restrict Key” and set a name for it (I set it to “DougScore”). Under “Application Restrictions,” we’re going to set it to “HTTP referrers” and add http://localhost:3000 for now. Under “API Restrictions” select the “Google Sheets API” and save. We should be good to go on this end.

在邊欄中,轉到“憑據”,單擊“創建憑據”按鈕,然后選擇“ API密鑰”。 單擊“限制鍵”并為其設置一個名稱(我將其設置為“ DougScore”)。 在“應用程序限制”下,我們將其設置為“ HTTP Referrers”,并立即添加http://localhost:3000 。 在“ API限制”下,選擇“ Google Sheets API”并保存。 我們應該為此而努力。

連接 (The Connection)

Now that we have an API key, head back over to the application code and create a new file called config.js . Input your API key and the spreadsheet ID into it.

現在我們有了一個API密鑰,回到應用程序代碼并創建一個名為config.js的新文件。 在其中輸入您的API密鑰和電子表格ID。

export default {apiKey: "YOUR_API_KEY",discoveryDocs: ["https://sheets.googleapis.com/$discovery/rest?version=v4"],spreadsheetId: "1KTArYwDWrn52fnc7B12KvjRb6nmcEaU6gXYehWfsZSo"
};

Now, we’ll need the Google API library, so we’ll use our index.html file inside the public library after our <div id="root"></div>

現在,我們需要Google API庫,因此在<div id="root"> </ div>之后,我們將在public庫中使用index.html文件

<!DOCTYPE html>
<html lang="en"><head><!-- Stuff --></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script src="https://apis.google.com/js/api.js"></script><!-- Stuff --></body>
</html>

This will give us access to window.gapi which we’ll use to connect to the Sheets API. For more information on it, head over to Google’s Docs.

這將使我們能夠訪問window.gapi ,我們將使用它來連接到Sheets API。 有關更多信息,請訪問Google的文檔 。

數據 (The Data)

Now that we have access to the API, let’s establish the connection to it. The best place to do that would be inside the componentDidMount lifecycle of the CarList component we created earlier. Let’s head over there.

現在我們已經可以訪問該API,讓我們建立與其的連接。 最好的選擇是在我們之前創建的CarList組件的componentDidMount生命周期內。 我們去那邊。

componentDidMount() {// 1. Load the JavaScript client library.window.gapi.load("client", this.initClient);
}

window.gapi.load accepts a callback so our initClient function looks like this:

window.gapi.load接受回調,因此我們的initClient函數如下所示:

initClient = () => {// 2. Initialize the JavaScript client library.window.gapi.client.init({apiKey: config.apiKey,// Your API key will be automatically added to the Discovery Document URLs.discoveryDocs: config.discoveryDocs}).then(() => {// 3. Initialize and make the API request.load(this.onLoad);});
};

A few things are introduced here. config is coming from the config.js file we created earlier, so don’t forget to do import config from “../config”; at the top of the CarList.js file.

這里介紹一些事情。 config來自我們之前創建的config.js文件,因此不要忘記import config from “../config”;CarList.js文件的頂部。

load is a function that we’ll be creating now. It will be in charge of connecting to the right spreadsheet, formatting the data correctly, and returning it to the component within the this.onLoad callback (or returning an error if we messed something up).

load是我們現在要創建的函數。 它將負責連接到正確的電子表格,正確格式化數據,并將其返回到this.onLoad回調中的組件(或者如果我們搞砸了則返回錯誤)。

I wanted to separate that logic from the component to keep the files small and fairly readable. Let’s create a new folder called helpers inside src and put a spreadsheet.js file in there.

我想將該邏輯與組件分開,以使文件更小且更易讀。 讓我們在src創建一個名為helpers的新文件夾,然后在其中放置一個spreadsheet.js

import config from "../config";
/*** Load the cars from the spreadsheet* Get the right values from it and assign.*/
export function load(callback) {window.gapi.client.load("sheets", "v4", () => {window.gapi.client.sheets.spreadsheets.values.get({spreadsheetId: config.spreadsheetId,range: "Sheet1!A4:T"}).then(response => {const data = response.result.values;
const cars = data.map(car => ({year: car[0],make: car[1],model: car[2]})) || [];
callback({cars});},response => {callback(false, response.result.error);});});
}

So here we’re invoking the sheets API and getting values from the spreadsheet by passing the spreadsheetId and the range . The promise returns two responses: one if there is data and one if there is an error. The response values are an array of arrays where each one is a row within the spreadsheet.

因此,在這里,我們要調用工作表API,并通過傳遞spreadsheetIdrange從電子表格中獲取值。 承諾返回兩個響應:一個響應(如果有數據)和一個錯誤(有錯誤)。 響應值是一個數組數組,其中每個都是電子表格中的一行。

顯示器 (The Display)

Now that we have data back inside the CarList component, we can start setting up the display for it. Inside the initClient function, we had the load(this.onLoad) function, so let’s pick up there.

現在我們已經有數據返回到CarList組件內部,我們可以開始為其設置顯示了。 在initClient函數內部,我們有load(this.onLoad)函數,因此讓我們開始學習。

onLoad = (data, error) => {if (data) {const cars = data.cars;this.setState({ cars });} else {this.setState({ error });}
};

If the load function within spreadsheet.js returns data, we set the cars state to that data. Otherwise we set an error state to show to our users that something went wrong.

如果spreadsheet.js .js中的load函數返回數據,則將cars狀態設置為該數據。 否則,我們將設置一個error狀態,以向用戶顯示出了問題。

默認狀態 (Default state)

Since data won’t be available instantly, we need to set up a default state for our component.

由于無法立即獲得數據,因此我們需要為組件設置默認狀態。

state = {cars: [],error: null
}

渲染 (Render)

Now inside the render function we can display the state:

現在,在render函數中,我們可以顯示狀態:

render() {const { cars, error } = this.state;if (error) {return <div>{this.state.error}</div>;}return (<ul>{cars.map((car, i) => (<li key={i}>{car.year} {car.make} {car.model}</li>))}</ul>);
}

Here we’re destructuring the state (ES6 FTW ??) and first checking if there is an error. If not, we’re mapping over the cars and displaying them in an unordered list.

在這里,我們要解構狀態(ES6 FTW ??),并首先檢查是否存在錯誤。 如果沒有,我們將在汽車上繪制地圖,并將其顯示在無序列表中。

部署方式 (Deployment)

Now that we have our super beautiful list of cars Doug has reviewed, we can go ahead and share it with the world. Since it will be a static website, I am going to deploy it to Netlify using their CLI. For that we’re going to stop our localhost and run the following commands:

現在我們有了道格已審查的超級精美汽車清單,我們可以繼續與世界分享。 由于它將是一個靜態網站,因此我將使用其CLI將其部署到Netlify 。 為此,我們將停止本地主機并運行以下命令:

yarn build

This will create a build folder within the application which will be production ready. Now all you have to do is:

這將在應用程序中創建一個準備就緒的build文件夾。 現在您要做的就是:

npm install netlify-cli -g
netlify deploy

When it asks, make sure you put in build as the Path to deploy? (current dir) .

在詢問時,請確保將build作為Path to deploy? (current dir) Path to deploy? (current dir)

Netlify is going to do its thing and show you the final URL (mine is https://laughing-yonath-118f58.netlify.com ?)

Netlify將執行其操作并向您顯示最終URL(我的網址是https://laughing-yonath-118f58.netlify.com嗎?)

If you try to access the one you created, you’ll see an error in your console because your URL wasn’t added to the Google API console. Go ahead and add the URL you need, and after that everything should be working as expected.

如果您嘗試訪問自己創建的控制臺,則會在控制臺中看到錯誤消息,因為您的網址未添加到Google API控制臺中。 繼續并添加所需的URL,然后一切都將按預期工作。

結束 (The End)

I hope all of this made sense. You can now work your magic on adding features to that list such as sorting, filtering, pagination, search, comparison, and so on. And when Doug adds another car to that list, the app will be automatically updated with the new information.

我希望所有這些都是有道理的。 現在,您可以發揮神奇的作用,向該列表添加功能,例如排序,過濾,分頁,搜索,比較等等。 當道格將另一輛車添加到該列表時,該應用程序將自動更新為新信息。

If this tutorial made sense, give it a ?? and share it with a friend. If you want to tell me it sucked or you have any more questions, comment below or yell at me on Twitter, I really don’t mind. If Doug is reading this, hey Doug ??!

如果本教程有意義,請給它一個? 并與朋友分享。 如果您想告訴我它很爛,或者您還有其他問題,請在下面評論或在Twitter上對我大喊,我真的不介意。 如果Doug正在閱讀此內容,則嘿Doug ??!

翻譯自: https://www.freecodecamp.org/news/how-to-deploy-a-react-application-to-netlify-that-reads-from-a-google-sheet-97a015806c47/

react數據從本地讀取

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394257.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394257.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394257.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

leetcode743. 網絡延遲時間(迪杰斯特拉算法)

有 N 個網絡節點&#xff0c;標記為 1 到 N。 給定一個列表 times&#xff0c;表示信號經過有向邊的傳遞時間。 times[i] (u, v, w)&#xff0c;其中 u 是源節點&#xff0c;v 是目標節點&#xff0c; w 是一個信號從源節點傳遞到目標節點的時間。 現在&#xff0c;我們從某個…

在線python視頻教程_【好程序員】2019 Python全套視頻教程2

2019千鋒好程序員全新Python教程&#xff0c;深入淺出的講解Python語言的基礎語法&#xff0c;注重基本編程能力訓練&#xff0c;深入解析面向對象思想&#xff0c;數據類型和變量、運算符、流程控制、函數、面向對象、模塊和包、生成器和迭代器。教程列表&#xff1a;千鋒Pyth…

洛谷——P1546 最短網絡 Agri-Net

P1546 最短網絡 Agri-Net 題目背景 農民約翰被選為他們鎮的鎮長&#xff01;他其中一個競選承諾就是在鎮上建立起互聯網&#xff0c;并連接到所有的農場。當然&#xff0c;他需要你的幫助。 題目描述 約翰已經給他的農場安排了一條高速的網絡線路&#xff0c;他想把這條線路共享…

漫談單點登錄(SSO)(淘寶天貓)(轉載)

1. 摘要 &#xff08; 注意&#xff1a;請仔細看下摘要&#xff0c;留心此文是否是您的菜&#xff0c;若浪費寶貴時間&#xff0c;深感歉意&#xff01;&#xff01;&#xff01;&#xff09; SSO這一概念由來已久&#xff0c;網絡上對應不同場景的成熟SSO解決方案比比皆是&…

mysql mdl 鎖_MySQL MDL鎖

MDL全稱為metadata lock&#xff0c;即元數據鎖。MDL鎖主要作用是維護表元數據的數據一致性&#xff0c;在表上有活動事務(顯式或隱式)的時候&#xff0c;不可以對元數據進行寫入操作。因此從MySQL5.5版本開始引入了MDL鎖&#xff0c;來保護表的元數據信息&#xff0c;用于解決…

Card Game Again CodeForces - 818E (雙指針)

大意: 給定序列, 求多少個區間積被k整除. 整除信息滿足單調性, 顯然雙指針. 具體實現只需要考慮k的素數向量, 對每一維維護個指針即可. 這題看了下cf其他人的做法, 發現可以直接暴力, 若當前的前綴積模k為0, 暴力向前求出第一個后綴積為0的位置即可, 復雜度是$O(n)$的并且相當好…

pacf和acf_如何通過Wordpress API,ACF和Express.js使Wordpress更加令人興奮

pacf和acfby Tyler Jackson泰勒杰克遜(Tyler Jackson) 如何通過Wordpress API&#xff0c;ACF和Express.js使Wordpress更加令人興奮 (How to make Wordpress more exciting with the Wordpress API, ACF, & Express.js) I’ve been working with Wordpress since it’s pr…

python運行出現數據錯誤_Python運行出錯情況

1、錯誤內容&#xff1a;You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory str). It is highly recommended that you instead just switch your application to Unicode strings.錯誤描述&#x…

leetcode95. 不同的二叉搜索樹 II(遞歸)

給定一個整數 n&#xff0c;生成所有由 1 ... n 為節點所組成的 二叉搜索樹 。示例&#xff1a;輸入&#xff1a;3 輸出&#xff1a; [[1,null,3,2],[3,2,null,1],[3,1,null,null,2],[2,1,3],[1,null,2,null,3] ] 解釋&#xff1a; 以上的輸出對應以下 5 種不同結構的二叉搜索樹…

數據結構探險系列—棧篇-學習筆記

數據結構探險—棧篇 什么是棧&#xff1f; 古代棧就是牲口棚的意思。 棧是一種機制&#xff1a;后進先出 LIFO&#xff08;last in first out&#xff09; 電梯 棧要素空棧。棧底&#xff0c;棧頂。沒有元素的時候&#xff0c;棧頂和棧底指向同一個元素&#xff0c;如果加入新元…

MYSQL遠程登錄權限設置 ,可以讓Navicat遠程連接服務器的數據庫

Mysql默認關閉遠程登錄權限&#xff0c;如下操作允許用戶在任意地點登錄&#xff1a;1. 進入mysql&#xff0c;GRANT ALL PRIVILEGES ON *.* TO root% IDENTIFIED BY WITH GRANT OPTION;IDENTIFIED BY后跟的是密碼&#xff0c;可設為空。2. FLUSH privileges; 更新Mysql為了安…

time series 時間序列 | fractional factorial design 部分要因試驗設計

作業&#xff1a; 1) A plot of data from a time series, which shows a cyclical pattern – please show a time series plot and identify the length of the major cycle. 2) Data from a full factorial or fractional factorial experiment with at least 2 factors –…

如何在Go中編寫防彈代碼:不會失敗的服務器工作流程

by Tal Kol通過塔爾科爾 如何在Go中編寫防彈代碼&#xff1a;不會失敗的服務器工作流程 (How to write bulletproof code in Go: a workflow for servers that can’t fail) From time to time you may find yourself facing a daunting task: building a server that really …

越獄第一至五季/全集迅雷下載

越獄 第一季 Prison Break Season 1 (2005) 本季看點&#xff1a;邁克爾斯科菲爾德是一頭陷于絕境欲拼死一搏的怒獅——他的哥哥林肯巴羅斯被認定犯有謀殺罪被投入了福克斯河監獄的死囚牢。雖然所有的證據都指出林肯就是兇手&#xff0c;邁克爾堅信兄長是無辜的。林肯的死刑執行…

leetcode面試題 16.19. 水域大小(深度優先搜索)

你有一個用于表示一片土地的整數矩陣land&#xff0c;該矩陣中每個點的值代表對應地點的海拔高度。若值為0則表示水域。由垂直、水平或對角連接的水域為池塘。池塘的大小是指相連接的水域的個數。編寫一個方法來計算矩陣中所有池塘的大小&#xff0c;返回值需要從小到大排序。 …

java -jar 默認參數_JAVA入門學習指南,建議收藏

如果你不懂Java 并且想認真學習接觸了解一下Java的語法&#xff0c;建議把這篇文章收藏了&#xff0c;多看幾遍&#xff0c;應該可以初步掌握Java 大部分基礎的語法 。 讓我們出發吧&#xff01;ps:本文有點長&#xff0c;耐心閱讀 。〇&#xff0c;編程環境工程項目推薦使用ID…

【RabbitMQ】 WorkQueues

消息分發 在【RabbitMQ】 HelloWorld中我們寫了發送/接收消息的程序。這次我們將創建一個Work Queue用來在多個消費者之間分配耗時任務。 Work Queues&#xff08;又稱為&#xff1a;Task Queues&#xff09;的主要思想是&#xff1a;盡可能的減少執行資源密集型任務時的等待時…

python matplotlib庫安裝出錯_使用pip install Matplotlib時出現內存錯誤

我使用的是Python2.7&#xff0c;如果我試圖安裝Matplotlib&#xff0c;如果我使用“pip install Matplotlib”&#xff0c;就會出現這個錯誤Exception:Traceback (most recent call last):File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line …

笑看職場什么程序員才搶手,什么樣的程序員漲薪多?

?程序員&#xff0c;怎么才算合格&#xff0c;不好說吧&#xff1b;他就像銷售一樣&#xff0c;一名銷售員&#xff0c;比如網絡銷售賣茶葉&#xff0c;他賣茶葉很厲害呀&#xff0c;可是你讓他去銷售房地產&#xff0c;就算他有點銷售的基礎&#xff0c;也要重新去學怎么銷售…

Android畫布Canvas裁剪clipRect,Kotlin

Android畫布Canvas裁剪clipRect&#xff0c;Kotlin private fun mydraw() {val originBmp BitmapFactory.decodeResource(resources, R.mipmap.pic).copy(Bitmap.Config.ARGB_8888, true)val newBmp Bitmap.createBitmap(originBmp.width, originBmp.height, Bitmap.Config.A…