У меня есть этот PrivateRoute, где, если пользователь аутентифицирован, визуализируйте этот защищенный компонент, если нет, перенаправьте пользователя на страницу регистрации.
Теперь все работает нормально. Если я вошел в систему, компонент защищенного компонента (post/new
) рендерится, но когда я перефразирую sh, компонент /register
рендерится.
import React from "react";
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => {
return (
<Route
{...rest}
render={props =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to="/register"/>
)
}
/>
);
};
const mapStateToProps = state => {
return {isAuthenticated: state.auth.isAuthenticated};
};
export default connect(mapStateToProps)(PrivateRoute);
Приложение. js
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import LandingPage from "./components/LandingPage";
import RegistrationForm from "./components/RegistrationForm";
import LoginForm from "./components/LoginForm";
import NotFoundPage from "./components/NotFoundPage";
import Feed from "./components/Feed";
import { getCurrentUser } from "./actions/userActions";
import { addpost } from "./actions/userActions";
import { connect } from "react-redux";
import NewpostForm from "./components/NewpostForm";
import Header from "../client/components/Header";
import UserProfile from "./components/UserProfile";
import PrivateRoute from "./components/PrivateRoute";
import ResetPasswordPage from "./components/ResetPasswordPage";
class App extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const authToken = localStorage.getItem("authToken");
if (authToken) {
this.props.dispatch({ type: "TOKEN_VERIFICATION_STARTS" });
this.props.dispatch(getCurrentUser(authToken));
}
}
render() {
const isIdentifyingToken = this.props.auth.isIdentifyingToken;
return (
<div>
{isIdentifyingToken ? null : (
<Router>
{/* <Header /> */}
<Switch>
<Route exact path="/" component={LandingPage} />
<Route path="/register" component={RegistrationForm} />
<Route path="/login" component={LoginForm} />
<Route path="/feed" component={Feed} />
<PrivateRoute
path="/post/new"
component={NewpostForm}
/>
<Route path="/profile" component={UserProfile} />
<Route path="/reset-password" component={ResetPasswordPage} />
<Route component={NotFoundPage} />
</Switch>
</Router>
)}
</div>
);
}
}
const mapStateToProps = state => {
return state;
};
export default connect(mapStateToProps)(App);
store. js
import {createStore, applyMiddleware} from "redux"
import thunk from "redux-thunk"
import rootReducer from "./reducers/index"
const store = createStore(rootReducer, applyMiddleware(thunk))
export default store
auth. js
const initialState = {
isAuthInProgress: false,
isAuthenticated: false,
authError: null,
user: null,
isIdentifyingToken: false,
token: localStorage.getItem("authToken") || ""
}
const auth = (state=initialState, action) => {
switch(action.type) {
case "AUTH_STARTS":
return {...state,
isAuthInProgress: true,
authError: null
}
case "AUTH_SUCCESS":
return {...state,
isAuthInProgress: false,
authError: null,
isAuthenticated: true,
user: action.data.user,
isIdentifyingToken: false,
// token: action.data.token
}
case "AUTH_ERROR":
return {...state,
isAuthInProgress: false,
authError: action.data.error,
isAuthenticated: false,
user: null
}
case "TOKEN_VERIFICATION_STARTS":
return {...state,
isAuthInProgress: true,
authError: null,
isIdentifyingToken: true
}
case "LOGOUT_USER":
return {...state,
isAuthenticated: false,
token: localStorage.removeItem("authToken"),
user: null
}
default:
return state
}
}
export default auth