Javascript &引用;GAPI未定义“GAPI”;消息
我试图使用GoogleSheetsAPI将其包含在我的web应用程序中,但我一直收到一个错误,指定gapi库未定义。我尝试使用ComponentDidMount生命周期方法延迟对服务器的请求,甚至在该方法中使用超时,但我一直收到相同的错误。如何定义gapi库以便在我的应用程序中使用Javascript &引用;GAPI未定义“GAPI”;消息,javascript,reactjs,google-sheets,Javascript,Reactjs,Google Sheets,我试图使用GoogleSheetsAPI将其包含在我的web应用程序中,但我一直收到一个错误,指定gapi库未定义。我尝试使用ComponentDidMount生命周期方法延迟对服务器的请求,甚至在该方法中使用超时,但我一直收到相同的错误。如何定义gapi库以便在我的应用程序中使用 import React from 'react'; var CLIENT_ID = ''; var SCOPES = ["https://www.googleapis.com/auth/spreadsheets.
import React from 'react';
var CLIENT_ID = '';
var SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"];
export default class MyNavbar extends React.Component {
constructor(props) {
super(props);
}
componentDidMount(){
this.checkAuth();
}
/**
* Check if current user has authorized this application.
*/
checkAuth(){
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, this.handleAuthResult());
}
/**
* Handle response from authorization server.
*
* @param {Object} authResult Authorization result.
*/
handleAuthResult(authResult) {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
loadSheetsApi();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
authorizeDiv.style.display = 'inline';
}
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* @param {Event} event Button click event.
*/
handleAuthClick(event) {
gapi.auth.authorize(
{client_id: CLIENT_ID, scope: SCOPES, immediate: false},
handleAuthResult);
return false;
}
/**
* Load Sheets API client library.
*/
loadSheetsApi() {
var discoveryUrl =
'https://sheets.googleapis.com/$discovery/rest?version=v4';
gapi.client.load(discoveryUrl).then(listMajors);
}
/**
* Print the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
listMajors() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: 'Class Data!A2:E',
}).then(function(response) {
var range = response.result;
if (range.values.length > 0) {
appendPre('Name, Major:');
for (i = 0; i < range.values.length; i++) {
var row = range.values[i];
// Print columns A and E, which correspond to indices 0 and 4.
appendPre(row[0] + ', ' + row[4]);
}
} else {
appendPre('No data found.');
}
}, function(response) {
appendPre('Error: ' + response.result.error.message);
});
}
/**
* Append a pre element to the body containing the given message
* as its text node.
*
* @param {string} message Text to be placed in pre element.
*/
appendPre(message) {
var pre = document.getElementById('output');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
render(){
return (
<div>
<h1>Hello World My Name Is Justin 2</h1>
<div id="authorize-div"></div>
<pre id="output"></pre>
</div>
);
}
}
从“React”导入React;
var客户端ID=“”;
变量作用域=[”https://www.googleapis.com/auth/spreadsheets.readonly"];
导出默认类MyNavbar扩展React.Component{
建造师(道具){
超级(道具);
}
componentDidMount(){
this.checkAuth();
}
/**
*检查当前用户是否已授权此应用程序。
*/
checkAuth(){
gapi.auth.authorize(
{
“客户id”:客户id,
“scope”:SCOPES.join(“”),
“立即”:真
},this.handleAuthResult());
}
/**
*处理来自授权服务器的响应。
*
*@param{Object}authResult授权结果。
*/
handleAuthResult(authResult){
var authorizeDiv=document.getElementById('authorized-div');
if(authResult&!authResult.error){
//隐藏身份验证UI,然后加载客户端库。
authorizeDiv.style.display='none';
loadSheetsApi();
}否则{
//显示授权UI,允许用户通过
//单击“授权”按钮。
authorizeDiv.style.display='inline';
}
}
/**
*响应用户单击“授权”按钮,启动身份验证流。
*
*@param{Event}Event按钮单击事件。
*/
handleAuthClick(事件){
gapi.auth.authorize(
{client_id:client_id,scope:SCOPES,immediate:false},
手工(结果);
返回false;
}
/**
*加载工作表API客户端库。
*/
loadSheetsApi(){
发现变种=
'https://sheets.googleapis.com/$discovery/rest?版本=v4';
gapi.client.load(discoveryUrl).then(listMajors);
}
/**
*在样本电子表格中打印学生姓名和专业:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
列表主修科目(){
gapi.client.sheets.spreadsheets.values.get({
电子表格ID:'1BXIMV0xRA5NFMDKVBDBZJGMUQPTLBS74OGVE2UPMS',
范围:“类数据!A2:E”,
}).然后(功能(响应){
var范围=响应。结果;
如果(range.values.length>0){
appendPre('姓名,专业:');
对于(i=0;i
您需要在index.html文件中的bundle.js之前加载gapi
库,或者更好地,您可以使用react async loader加载gapi
js脚本async。
以下是您如何做到这一点:
import React, { Component, PropTypes } from 'react';
import asyncLoad from 'react-async-loader'; // for loading script tag asyncly
// For making gapi object passed as props to our component
const mapScriptToProps = state => ({
gapi: {
globalPath: 'gapi',
url: 'https://your-gapi-url'
}
});
// decorate our component
@asyncLoad(mapScriptToProps)
class yourComponent extends Component {
componentDidMount() {
// Check is gapi loaded?
if (this.props.gapi !== null) {
this.checkAuth();
}
}
componentWillReceiveProps({ gapi }) {
if (gapi!== null) {
this.checkAuth();
}
}
checkAuth = () => {
// Better check with window and make it available in component
this.gapi = window.gapi;
this.gapi.auth.authorize({
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, this.handleAuthResult);
}
handleAuthResult = (authData) => {
// Your auth loagic...
}
render() {
return ( <div>
{ this.props.gapi &&
<YourSpreadsheetOrWhatever data={ this.getData() } />
}
</div>)
}
}
import React,{Component,PropTypes}来自'React';
从“反应异步加载程序”导入异步加载;//用于异步加载脚本标记
//用于将gapi对象作为道具传递给我们的组件
常量mapScriptToProps=状态=>({
gapi:{
全球路径:“gapi”,
网址:'https://your-gapi-url'
}
});
//装饰我们的部件
@异步加载(mapScriptToProps)
类yourComponent扩展组件{
componentDidMount(){
//检查gapi是否已加载?
if(this.props.gapi!==null){
this.checkAuth();
}
}
componentWillReceiveProps({gapi}){
如果(gapi!==null){
this.checkAuth();
}
}
checkAuth=()=>{
//最好使用窗口进行检查,并使其在组件中可用
this.gapi=window.gapi;
this.gapi.auth.authorize({
“客户id”:客户id,
“scope”:SCOPES.join(“”),
“立即”:真
},此。handleAuthResult);
}
handleAuthResult=(authData)=>{
//你的授权书。。。
}
render(){
报税表(
{this.props.gapi&&
}
)
}
}
尝试用此代码替换您的代码,并检查其是否有效。在此处尝试此操作
import React from 'react';
import asyncLoad from 'react-async-loader'; // for loading script tag asyncly `npm i --save react-async-loader`
const CLIENT_ID = '';
const SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"];
// For making gapi object passed as props to our component
const mapScriptToProps = state => ({
// gapi will be this.props.gapi
gapi: {
globalPath: 'gapi',
url: 'https://your-gapi-url'
}
});
@asyncLoad(mapScriptToProps)
class MyNavbar extends React.Component {
constructor(props) {
super(props);
this.gapi = null;
// You need to bind methods to this class's object context. (i.e this)!
this.checkAuth = this.checkAuth.bind(this);
this.handleAuthResult = this.authResult.bind(this);
this.handleAuthClick = this.handleAuthClick.bind(this);
this.loadSheetsApi = this.loadSheetsApi.bind(this);
this.listMajors = this.listMajors.bind(this);
}
componentDidMount() {
// Check is gapi loaded?
if (this.props.gapi !== null) {
this.checkAuth();
}
}
componentWillReceiveProps({ gapi }) {
if (gapi!== null) {
this.checkAuth();
}
}
/**
* Check if current user has authorized this application.
*/
checkAuth() {
// this will give you an error of gapi is not defined because there is no
// reference of gapi found globally you cannot access global object which are
// not predefined in javascript( in this case its window.gapi ).
// properties added by Programmer cannot be accessed directly( if it's not in the same file as well as the same scope!) in commonjs modules. Because they
// don't' run in a global scope. Any variable in another module which is not
// exported, will not be available to other modules.
this.gapi = window.gapi; // you can do like this. Now you can access gapi in all methods if this class.
this
.gapi
.auth
.authorize({
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, this.handleAuthResult());
}
/**
* Handle response from authorization server.
*
* @param {Object} authResult Authorization result.
*/
handleAuthResult(authResult) {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
loadSheetsApi();
} else {
// Show auth UI, allowing the user to initiate authorization by clicking
// authorize button.
authorizeDiv.style.display = 'inline';
}
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* @param {Event} event Button click event.
*/
handleAuthClick(event) {
// gapi.auth.authorize( here also gapi is not defined
this
.gapi
.auth
.authorize({
client_id: CLIENT_ID,
scope: SCOPES,
immediate: false
}, handleAuthResult);
return false;
}
/**
* Load Sheets API client library.
*/
loadSheetsApi() {
var discoveryUrl = 'https://sheets.googleapis.com/$discovery/rest?version=v4';
// also will give your error
// for gapi being not defined.
// gapi.client.load(discoveryUrl).then(listMajors);
this
.gapi
.client
.load(discoveryUrl)
.then(listMajors);
}
/**
* Print the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
listMajors() {
this.gapi
.client
.sheets
.spreadsheets
.values
.get({spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms', range: 'Class Data!A2:E'})
.then(function (response) {
var range = response.result;
if (range.values.length > 0) {
appendPre('Name, Major:');
for (i = 0; i < range.values.length; i++) {
var row = range.values[i];
// Print columns A and E, which correspond to indices 0 and 4.
appendPre(row[0] + ', ' + row[4]);
}
} else {
appendPre('No data found.');
}
}, function (response) {
appendPre('Error: ' + response.result.error.message);
});
}
/**
* Append a pre element to the body containing the given message
* as its text node.
*
* @param {string} message Text to be placed in pre element.
*/
appendPre(message) {
// as you can see. You are accessing window.document as document.
// its fine because its defined in javascript (implicitly),
// not explicitly by programmer(here you!).
var pre = document.getElementById('output');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
render() {
return (
<div>
<h1>Hello World My Name Is Justin 2</h1>
<div id="authorize-div"></div>
<pre id="output"></pre>
</div>
);
}
}
export default MyNavbar;
从“React”导入React;
从“反应异步加载程序”导入异步加载;//用于异步加载脚本标记`npm i--save react async loader`
const CLIENT_ID=“”;
常量范围=[”https://www.googleapis.com/auth/spreadsheets.readonly"];
//用于将gapi对象作为道具传递给我们的组件
常量mapScriptToProps=状态=>({
//gapi将是this.props.gapi
gapi:{
全球路径:“gapi”,
网址:'https://your-gapi-url'
}
});
@异步加载(mapScriptToProps)
类MyNavbar扩展了React.Component{
建造师(道具){
超级(道具);
this.gapi=null;
//您需要将方法绑定到此类的对象上下文(即this)!
this.checkAuth=this.checkAuth.bind(this);
this.handleAuthResult=this.authResult.bind(this);
this.handleAuthClick=this.handleAuthClick.bind(this);
这是我的行李单
<script src="https://apis.google.com/js/api.js"></script>
let gapi = window.gapi;