【发布时间】:2021-08-02 09:47:24
【问题描述】:
我正在使用带有 react native 和 react 导航的 redux。登录时一切正常,但是当我注销时,它不会将我重定向回登录屏幕。后端的应用流程是:从 google 获取令牌 > 发送到 nodejs 服务器以使用相同的客户端 ID 进行验证 > 创建新用户或获取现有用户 > 使用 JWT 签署用户 ID > 发回新令牌。这是我的代码
Authnavigator.js
...
import {AuthScreens, DashboardScreens} from './AppNavigator';
// redux
import {useSelector} from 'react-redux';
const AuthNavigator = () => {
const userGoogleLogin = useSelector(state => state.userGoogleLogin);
const {loading, userInfo} = userGoogleLogin;
return (
<NavigationContainer>
{userInfo && <DashboardScreens />}
{!userInfo && <AuthScreens />}
</NavigationContainer>
);
};
export default AuthNavigator;
userAction.js
import axios from 'axios';
import {
GOOGLE_USER_LOGIN_REQUEST,
GOOGLE_USER_LOGIN_SUCCESS,
GOOGLE_USER_LOGIN_FAIL,
GOOGLE_USER_LOGOUT,
} from '../constants/userConstants';
import {GoogleSignin} from '@react-native-google-signin/google-signin';
export const googleLogin = idToken => async dispatch => {
try {
// request action
dispatch({type: GOOGLE_USER_LOGIN_REQUEST});
// set content type
const config = {
headers: {
'Content-Type': 'application/json',
},
};
// send post request
const {data} = await axios.post(
`https://still-eyrie-92675.herokuapp.com/api/auth/google`,
{
token: idToken,
},
);
// send back user data
dispatch({
type: GOOGLE_USER_LOGIN_SUCCESS,
payload: data,
});
} catch (error) {
dispatch({
type: GOOGLE_USER_LOGIN_FAIL,
payload: error,
});
}
};
export const googleLogout = () => async dispatch => {
await GoogleSignin.revokeAccess();
await GoogleSignin.signOut();
dispatch({type: GOOGLE_USER_LOGOUT});
};
userReducer.js
import {
GOOGLE_USER_LOGIN_REQUEST,
GOOGLE_USER_LOGIN_SUCCESS,
GOOGLE_USER_LOGIN_FAIL,
GOOGLE_USER_LOGOUT,
} from '../constants/userConstants';
export const userGoogleLoginReducer = (state = {}, action) => {
switch (action.type) {
case GOOGLE_USER_LOGIN_REQUEST:
return {loading: true};
case GOOGLE_USER_LOGIN_SUCCESS:
return {loading: false, userInfo: action.payload};
case GOOGLE_USER_LOGIN_FAIL:
return {loading: false, error: action.payload};
case GOOGLE_USER_LOGOUT:
return {};
default:
return state;
}
};
仪表板.js
...
// redux
import {useDispatch, useSelector} from 'react-redux';
import {googleLogout} from '../actions/userAction';
export default function Dashboard({navigation}) {
const dispatch = useDispatch();
const userGoogleLogin = useSelector(state => state.userGoogleLogin);
const {loading, error, userInfo} = userGoogleLogin;
return (
<Background>
<Logo />
<Header>Let’s start</Header>
<Paragraph>
Your amazing app starts here. Open you favorite code editor and start
editing this project.
</Paragraph>
<Button mode="outlined" onPress={() => dispatch(googleLogout())}>
Logout
</Button>
</Background>
);
}
【问题讨论】:
标签: reactjs react-native redux react-redux react-navigation