У меня есть проект, в котором пользователь имеет доступ к своей панели инструментов, после того как пользователь вошел в систему, он может перейти к определенным страницам (ссылкам)
Пример страниц, которые он может посетить:
Profile
-View profile
-Edit profile
основной маршрут, который отображает панель мониторинга:
localhost / dashboard / home
Когда пользователь нажимает Просмотреть профиль ссылку он будетбыть перенаправленным на страницу просмотра, отображаемую по маршруту
панель инструментов / пациент /: PatientCode / профиль
Теперь, когда я обновляю страницу * Просмотр профиля **Я буду перенаправлен обратно на страницу панели инструментов, это вызвано повторным рендерингом компонента App и проверкой того, что состояние авторизации пользователя будет AUTHENTICATED и, следовательно, будет перенаправлено обратноto / dashboard / home .
Мой вопрос: как вернуть пользователя туда, где он был до обновления браузера ?!
Обратите внимание, что я использую Redux для управления состоянием
, вот мой App.js
class App extends Component {
componentDidMount() {
this.checkAuthStatus();
}
checkAuthStatus() {
const accessToken = sessionStorage.getItem("accessToken");
if (!accessToken) {
this.props.signOut();
this.props.history.push("/");
} else {
const userCode = sessionStorage.getItem("userCode");
const patientCode = sessionStorage.getItem("patientCode");
const accountType = sessionStorage.getItem("accountType");
const accessTokenExpDate = Number(sessionStorage.getItem("expDate"));
if (accessTokenExpDate * 1000 <= new Date().getTime()) {
console.log("logging out -> token expired");
this.props.signOut();
this.props.history.push("/");
} else {
const userData = {
accessToken,
userCode,
patientCode,
accessTokenExpDate,
accountType
};
this.props.onAuthSuccess(userData);
this.props.lastVisitedPage === null
? this.props.history.push("/dashboard/home")
: this.props.history.push(this.props.lastVisitedPage);
}
}
}
get authenticatedRoutes() {
return (
<AuthenticatedWrapper>
<Switch>
<Route path="/dashboard/home" component={Dashboard} />
<Route
path="/dashboard/patient/:patientCode/profile"
component={Profile}
/>
<Route
exact
path="/dashboard/patient/:patientCode/edit"
component={Dashboard}
/>
<Route exact path="/contact" />
<Route exact path="/doctors-portal" />
<Route exact path="/signout" component={Signout} />
<Route exact path="/404" component={NotFound} />
</Switch>
{this.props.authStatus === "AUTHENTICATED" ? (
<Watcher
onSessionExpired={this.onSessionExpired}
onUserInActivity={this.onUserInActivity}
/>
) : null}
</AuthenticatedWrapper>
);
}
get unAuthenticatedRoutes() {
return (
<UnAuthenticatedWrapper>
<Switch>
<Redirect exact from="/" to="/signin" />
<Route exact path="/signin" component={Signin} />
<Route exact path="/signup" component={Signup} />
<Route exact path="/404" component={NotFound} />
{/* <Redirect from="*" to="/404" /> */}
</Switch>
</UnAuthenticatedWrapper>
);
}
onSessionExpired = () => {
const { history } = this.props;
history.push("/signout");
};
onUserInActivity = () => {
const { history } = this.props;
history.push("/signout");
};
render() {
const { authStatus } = this.props;
console.log("Auth:", authStatus);
const headerClasses =
this.props.location.pathname === "/signin" ? "blueLinks" : "whiteLinks";
const appRoutes =
authStatus === "AUTHENTICATED"
? this.authenticatedRoutes
: this.unAuthenticatedRoutes;
const navLinks = ["signin", "signup", "contact", "doctors-portal"];
let header = <Header extraClasses={headerClasses} />;
let sidebar = <Sidebar navLinks={navLinks} hasUserView={false} />;
let mainClasses = classNames({
"big-container": authStatus === "AUTHENTICATED" ? true : false
});
return (
<Fragment>
<div className={mainClasses}>
{authStatus === "AUTHENTICATED" ? null : header}
{authStatus === "AUTHENTICATED" ? null : sidebar}
<BurgerIcon />
<main>{appRoutes}</main>
</div>
</Fragment>
);
}
}
Dashboard.js
class Dashboard extends Component {
state = {
cities: [],
areas: []
};
componentDidUpdate(prevProps) {
cmInit();
dropDownInit();
if (prevProps.searchResult.length !== this.props.searchResult.length) {
this.handleRedirect("/dashboard/search");
}
}
componentDidMount() {
this.props.getDashboardData(this.props.patientCode);
}
handleRedirect(pathName) {
this.props.history.push(pathName);
}
onSubmit = formData => {
this.setState({ isLoading: true });
this.props.onSearchSubmit(formData);
};
onGovernorateDropDownChange = e => {
const gov = e.target.value;
const cities = [];
let areas = null;
addresses.map(address => {
if (address.governorate === gov) {
address.cities.map(city => {
cities.push(city.name);
areas = city.areas;
});
}
});
this.setState({ cities, areas });
};
render() {
const {
accountType,
handleSubmit,
dashboardData,
initialPage
} = this.props;
const specializations = ["allergy and immunology", "spec2", "spec3"];
let dashboard = (
<div className="dashboard">
<div className="content">
<div className="row row-margin">
<div className="col l10 offset-m1 s12 person-banner">
<p>
Hello, {dashboardData !== null ? dashboardData.patientName : ""}
</p>
</div>
</div>
<div className="row row-margin">
<div className="col l10 offset-m1 s12 appointments-banner">
<h4>Appointments</h4>
<AppointmentCard
appointmentInfo={
dashboardData !== null
? dashboardData.upcomingAppointment
: null
}
title="Next appointment"
/>
<AppointmentCard
appointmentInfo={
dashboardData !== null
? dashboardData.previousAppointment
: null
}
title="Last appointment"
/>
</div>
</div>
<div className="row row-margin">
<div className="col l10 offset-m1 s12 search-banner">
<h4>Search</h4>
<SearchForm
onSubmit={handleSubmit(this.onSubmit)}
onStarClick={this.onStarClick}
addresses={addresses}
areas={this.state.areas}
cities={this.state.cities}
specializations={specializations}
onGovernorateDropDownChange={this.onGovernorateDropDownChange}
/>
</div>
</div>
<div className="row row-margin">
<div className="col l10 offset-m1 s12 doctors-banner">
<h4>My doctors</h4>
</div>
</div>
<div className="row row-margin">
<div className="col l10 offset-m1 s12 rated-doctors-banner">
<h4>Top rated doctors</h4>
</div>
</div>
</div>
</div>
);
if (this.props.isLoading) {
dashboard = <Loader />;
}
return (
<Fragment>
<Sidebar
hasUserView={true}
isFixed={true}
accountType={accountType}
extraClasses="hide-on-med-and-down"
/>
{dashboard}
</Fragment>
);
}
}