正在进行私有路由,如果用户未通过身份验证,但是useSelector()
尚未更新,则需要重定向。我还使用redux-devtools
App.js
const App = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(loadUser());
}, []);
return (
<Router>
<Switch>
<Route path='/' exact component={Home} />
<Route path='/register' exact component={Register} />
<Route path='/login' exact component={Login} />
<PrivateRoute component={Dashboard} path='/dashboard' exact />
</Switch>
</Router>
);
};
加载用户操作
const loadSuccess = (data) => {
return {
type: AUTH_SUCCESS,
payload: data,
};
};
const loadFailure = (errors) => {
return {
type: AUTH_FAILURE,
payload: errors,
};
};
export const loadUser = () => {
return async (dispatch) => {
try {
const res = await axios.get('/users/current');
dispatch(loadSuccess(res.data));
} catch (error) {
dispatch(loadFailure(error));
}
};
};
-编辑: authReducer.js
const initialState = {
token: null,
isAuth: false,
loading: true,
user: null,
errors: [],
};
const authReducer = (state = initialState, action) => {
switch (action.type) {
case AUTH_SUCCESS:
return {
...state,
token: localStorage.getItem('token'),
isAuth: true,
loading: false,
user: action.payload,
errors: [],
};
case AUTH_FAILURE:
return {
...state,
token: localStorage.removeItem('token'),
isAuth: false,
loading: true,
user: null,
errors: action.payload,
};
default:
return state;
}
};
export default authReducer;
PrivateRoute.js
const PrivateRoute = ({ component: Component, ...rest }) => {
const isAuth = useSelector((state) => state.authReducer.isAuth);
console.log(isAuth);
return (
<Route
{...rest}
render={(props) =>
isAuth ? <Component {...props} /> : <Redirect exact to='/' />
}
/>
);
};
export default PrivateRoute;
到目前为止,我相信操作已在主App.js
文件中正确调度,并且状态正在更新,如下图所示:
但是console.log(isAuth);
显示false
。
知道这里有什么问题吗?