我正試圖實施this谷歌日曆api的例子在一個反應js應用程序。香草JS例子在我的本地機器中工作得很好。但是在實施相同的反應時遇到很多麻煩。請檢查我的代碼如下:如何將Google Calendar API與React JS集成?
class App extends React.Component{
constructor(props) {
super(props);
var CLIENT_ID = '992549188018-3prg54pp18je3e3qhgcttgl11491c4dm.apps.googleusercontent.com';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];
var SCOPES = "https://www.googleapis.com/auth/calendar";
this.state = {
showAuthButton: false,
showSignOutButton: false
};
this.initClient = this.initClient.bind(this);
this.updateSigninStatus = this.updateSigninStatus.bind(this);
}
handleAuthClick(){
gapi.auth2.getAuthInstance().signIn();
}
handleSignoutClick(){
gapi.auth2.getAuthInstance().signOut();
}
handleClientLoad() {
gapi.load('client:auth2', this.initClient);
}
initClient(DISCOVERY_DOCS, CLIENT_ID, SCOPES) {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function() {
console.log(window.gapi);
// Listen for sign-in state changes.
window.gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
updateSigninStatus(isSignedIn) {
if (isSignedIn) {
this.setState({
showAuthButton: false,
showSignOutButton: true
})
//listUpcomingEvents();
//insertNewEvent();
} else {
this.setState({
showAuthButton: true,
showSignOutButton: false
})
}
}
componentDidMount(){
this.handleClientLoad();
}
render(){
let authButton = <button id="authorize-button" onClick={this.handleAuthClick.bind(this)}>Authorize</button>
let signOutButton = <button id="signout-button" onClick={this.handleSignoutClick.bind(this)}>Sign Out</button>
return(
<div className="container">
{this.state.showAuthButton ? authButton : null}
{this.state.showSignOutButton ? signOutButton : null}
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
正在此錯誤截至目前:
Uncaught TypeError: Cannot read property 'isSignedIn' of null
請指引我繼續移動...
您在構造函數中將'CLIENT_ID'等定義爲變量,但試圖將其作爲'this.CLIENT_ID'來訪問它 – marzelin
@marzelin我已經更新了代碼,仍然出現相同的錯誤! –
要麼將config vars移動到組件外,以便可以通過'initClient'方法到達,或將配置數據分配給'this'對象並以此方式訪問它。 – marzelin