我正在尝试使用 GAPI 实现 Google 身份验证,并且我想将 GAPI 获取的用户的 userId 存储到 redux 存储中。我不知道如何将类组件变量传递到 redux 存储或操作调度程序中。有人可以帮我摆脱这个吗?
import { SIGN_IN, SIGN_OUT } from './types'
export const signIn = (dispatch, userId) => {
console.log('actions',userId)
dispatch(
{
type: SIGN_IN,
payload:userId
}
)
}
export const signOut = (dispatch) => {
dispatch(
{
type: SIGN_OUT
}
)
}
const mapStateToProps = (state,ownProps) => {
return {
isSignedIn: state.auth.isSignedIn
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
SignIn: () => signIn(dispatch),
SignOut: () => signOut(dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(GoogleAuth);
登录:() => 登录(dispatch,ownProps.toString()),
我觉得应该是
登录:(值)=> 登录(调度,值),
您可以在实际调度操作时传递值。一旦你有了用户 ID,你就可以做
this.props.SignIn(userId)
这将触发操作调度,您必须在其中传递类似的值
const mapDispatchToProps = (dispatch, ownProps) => {
return {
SignIn: (id) => signIn(dispatch,id),
SignOut: () => signOut(dispatch)
}
}
export const signIn = (userId) => {
return {
type: SIGN_IN,
payload: userId
};
};
export const signOut = () => {
return {
type: SIGN_OUT
};
};
对于您的 GoogleAuth 组件:
componentDidMount() {
window.gapi.load('client:auth2', () => {
window.gapi.client.init({
clientId: 'YOUR_CLIENT_ID',
scope: 'email'
}).then(() => {
this.auth = window.gapi.auth2.getAuthInstance(); //Assign the auth instance
this.onAuthChange(this.auth.isSignedIn.get()); //Update the auth state in store
this.auth.isSignedIn.listen(this.onAuthChange); //Wait for the auth state to change in future
});
});
}
onAuthChange = (isSignedIn) => {
if (isSignedIn) {
this.props.signIn(this.auth.currentUser.get().getId());
} else {
this.props.signOut();
}
};
const mapsStateToProps = (state) => {
return { isSignedIn: state.auth.isSignedIn };
}
export default connect(mapsStateToProps, { signIn, signOut })(GoogleAuth);