通过在 HTML 标头中包含官方 Google 客户端 API,您走在了正确的轨道上。这不太理想——如果 Google 将(浏览器)客户端 API 作为 npm 模块提供,你可以import 会很好。但他们没有(我看到),所以我认为你正在做的很好。
然后是“我如何以对 React/Redux 友好的方式使用它?”的问题。 Redux 是一种管理应用程序状态的机制。 Google API 不是您的应用程序的一部分(尽管您对它的操作可能会告知您的应用程序的状态)。
验证您是否有权访问 Google API 很容易:您只需从您的一个组件的 componentDidMount 方法进行调用,然后记录控制台日志:
class MyComp extends React.Component {
componentDidMount() {
// this is taken directly from Google documentation:
// https://developers.google.com/api-client-library/javascript/start/start-js
function start() {
// 2. Initialize the JavaScript client library.
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
// clientId and scope are optional if auth is not required.
'clientId': 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
'scope': 'profile',
}).then(function() {
// 3. Initialize and make the API request.
return gapi.client.request({
'path': 'https://people.googleapis.com/v1/people/me',
})
}).then(function(response) {
console.log(response.result);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
};
// 1. Load the JavaScript client library.
gapi.load('client', start);
},
}
如果您在控制台上没有看到您所期望的内容,则说明 gapi 未按预期加载。如果发生这种情况,您可以提出更具体的问题!
如果您确实收到了响应,那么您现在知道如何调用 GAPI...但是如何以对 Redux 友好的方式使用它?
当您进行 GAPI 调用时,您可能希望以某种方式修改应用程序的状态(否则为什么要这样做?)例如,您可能会调用身份验证流程,当 GAPI 返回成功时,您的应用程序状态现在有loggedIn: true 或类似的(可能有很多其他的状态变化)。在哪里进行 GAPI 调用取决于您。如果您想在组件加载时执行此操作,则应在componentDidMount 中执行此操作。您通常还可能会发出 GAPI 调用以响应用户操作,例如单击按钮。
所以典型的流程是这样的:
// either in componentDidMount, or a control handler, usually:
someGapiCall()
.then(result => {
this.props.onGapiThing(result.whatever)
})
其中this.props.onGapiThing 是一个调度适当操作的函数,该操作会修改您的应用程序状态。
我希望这个概述能有所帮助...请随时跟进更具体的问题。