【发布时间】:2024-04-22 06:45:02
【问题描述】:
有人可以帮我弄清楚为什么我的 Google OAuth 不能与我的应用一起使用吗?我正在使用我过去构建的另一个应用程序运行完全相同的代码,并且在该应用程序上似乎可以顺利登录和退出,但与我目前正在使用的应用程序不同。除非我完全删除 mapStateToProps 函数,否则我什至看不到登录按钮。在这种情况下,按钮会出现,但显然没有按预期工作。有任何想法吗?我正在使用 Redux 和 action creators 和 reducers 来反映用户是否已登录。
GoogleOath.js
import React from 'react';
import { connect } from 'react-redux';
import { signIn, signOut } from '../actions';
class GoogleAuth extends React.Component {
componentDidMount() {
window.gapi.load('client:auth2', () => {
window.gapi.client.init({
clientId: '//// hidden ',
scope: 'email'
}).then(() => {
this.auth = window.gapi.auth2.getAuthInstance();
this.onAuthChange(this.auth.isSignedIn.get());
this.auth.isSignedIn.listen(this.onAuthChange);
});
});
}
onAuthChange = isSignedIn => {
if (isSignedIn) {
this.props.signIn(this.auth.currentUser.get().getId());
} else {
this.props.signOut();
}
};
onSignIn = () => {
this.auth.signIn();
};
onSignOut = () => {
this.auth.signOut();
};
renderAuthButton() {
if (this.props.isSignedIn === null) {
return null;
} else if (this.props.isSignedIn) {
return (
<button onClick={this.onSignOut} className='waves-effect waves-light social-icon btn google'>
<i className="fab fa-google"></i> Sign out</button>
);
} else {
return (
<button onClick={this.onSignIn} className='waves-effect waves-light social-icon btn google'>
<i className="fab fa-google"></i> Sign in</button>
);
}
}
render() {
return <div>{this.renderAuthButton()}</div>
}
};
const mapStateToProps = state => {
return { isSignedIn: state.auth.isSignedIn };
};
export default connect(
mapStateToProps,
{ signIn, signOut }
)(GoogleAuth);
Actions Index.js
import { SIGN_IN, SIGN_OUT } from './types';
export const signIn = (userId) => {
return {
type: SIGN_IN,
payload: userId
};
};
export const signOut = () => {
return {
type: SIGN_OUT
}
};
Reducers Index.js
import { combineReducers } from 'redux';
import authReducer from './authReducer';
export default combineReducers({
auth: authReducer
});
Reducers authReducer.js
import { SIGN_IN, SIGN_OUT } from '../actions/types';
const INITIAL_STATE = {
isSignedIn: null,
userId: null
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case SIGN_IN:
return { ...state, isSignedIn: true, userId: action.payload };
case SIGN_OUT:
return { ...state, IsSignedIn: false, userId: null };
default:
return state;
}
};
【问题讨论】:
标签: reactjs redux react-redux google-api-js-client