我正在构建一个登录页面示例来提高我的反应技能。然而,我无法解决有关React Router的问题。我成功地获得了身份验证,应用程序将我带到受保护的页面,但当我刷新此受保护页面中的页面时,它会显示空白页面。
当我尝试手动编写受保护的URL时,也会发生同样的情况。(空白屏幕(
这是PrivateRoute
export const PrivateRoute = ({
isAuthenticated,
component: Component,
...rest
}) => (
<Route {...rest} render={(props) => {
if (isAuthenticated) {
return <Component {...props} />
}
else {
return <Redirect to="/" />
}
}} />
);
const mapStateToProps = state => {
console.log(state.userReducer.token);
return {
isAuthenticated: !!state.userReducer.token
}
};
export default connect(mapStateToProps)(PrivateRoute);
这是PublicRoute
export const PublicRoute = ({ isAuthenticated, component: Component, ...rest}) => (
<Route {...rest} render={(props) => {
if (isAuthenticated) {
return <Redirect to="/logged" />
}
else {
return <Component {...props} />
}
}} />
);
const mapStateToProps = state => ({
isAuthenticated: !!state.userReducer.token
});
export default connect(mapStateToProps)(PublicRoute);
AppRouter
const AppRouter = () => {
return (
<BrowserRouter>
<div>
<PublicRoute path="/" component={LoginForm} exact />
<PrivateRoute path="/logged" component={LoggedPage} />
</div>
</BrowserRouter>
);
}
export default AppRouter;
最后是我创建的最后一个AppRouter
const jsx = (
<Provider store={createStore(reducers)}>
<AppRouter />
</Provider>
)
ReactDOM.render(jsx, document.getElementById('root'));
我感谢任何建议,提前感谢
当页面刷新时,它会丢失状态以及您的登录状态。您应该将一些数据放到本地存储中,以保留会话信息。在调度有关登录的操作之前,我将用户凭据保存到本地存储中。每当页面重新加载时,我都会从本地存储中获取数据,并将其作为登录操作进行调度。所以我保持我的会议开放。
export function signInUser(user) {
let userEmail = user.email;
let userPassword = user.password;
let credentials = {
email: userEmail,
password: userPassword
};
return dispatch => {
axios
.request({
method: "post",
url: loopBack + "/blogusers/login?include=user",
data: credentials
})
.then(response => {
//sets user data to local storage
localStorage.setItem("id", response.data.id);
localStorage.setItem("userId", response.data.userId);
localStorage.setItem("userName", response.data.user.userName);
localStorage.setItem("email", response.data.user.email);
return dispatch(signInSuccess(response.data));
})
.catch(error => {
return dispatch(signInFailure(error));
});
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
//if session information is lost it gets data from localstorage and set user data
export function setToken() {
return dispatch => {
let id = localStorage.getItem("id");
let userId = localStorage.getItem("userId");
let userName = localStorage.getItem("userName");
let email = localStorage.getItem("email");
let user = { id, userId, user: { email, userName } };
return dispatch(signInSuccess(user));
};
}