所以基本上我正在尝试设置受保护的路由。
这是我的 ProtectedRoute 组件:
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';
import { authenticate } from './actions';
const ProtectedRoute = ({
component: Component, authenticate, isAuthenticated, ...rest
}) => {
useEffect(() => {
authenticate();
});
return (
<Route
{...rest}
render={props => (isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to="/login" />
))
}
/>
);
};
ProtectedRoute.propTypes = {
component: PropTypes.elementType.isRequired,
authenticate: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
};
const mapStateToProps = state => ({
isAuthenticated: state.isAuthenticated,
});
export default connect(mapStateToProps, { authenticate })(ProtectedRoute);
这是验证操作:
const authenticate = () => dispatch => axios('http://localhost:8080/user', {
method: 'get',
withCredentials: true,
}).then((response) => {
dispatch({ type: 'AUTHENTICATE_SUCCESS', payload: response.data });
}).catch((error) => {
dispatch({ type: 'AUTHENTICATE_FAILURE' });
throw (error);
});
但是不幸的是,它不起作用,因为它会在身份验证过程完成之前重定向到渲染。我应该怎么做才能解决这个问题?我应该添加一个额外的布尔值来检查呈现任何内容之前是否完成了身份验证过程吗?还是有更好的方法?