При перенаправлении после загрузки компонента с использованием history.push - мой компонент отображается снова.Вызов функции componentDidMount()
для запуска дважды.
Вот упрощенный фрагмент одного из моих компонентов.Я хочу, чтобы componentDidMount()
запускался только один раз - и он работает, как и ожидалось, без history.push
.Но когда я добавляю history.push
- он загружается дважды.(То же самое происходит, если я использую Redirect
из react-router
)
import * as React from "react";
import { history } from "../../configureServices";
import { explore } from "../../routes";
export class WelcomeComponent extends React.Component<object, object> {
componentDidMount() {
// tslint:disable-next-line:no-console
console.log("componentDidMount");
history.replace(explore);
}
render() {
return <div />;
}
}
Консоль:
componentDidMount
componentDidMount
Хотелось бы найти способ запустить этот прогон только один раз.
Редактировать: Спасибо всем за ответы.Я собираюсь опубликовать небольшой фрагмент кода, а затем немного опубликовать скрипку.
--- Обновление:
Я использую React-Router.Я строю историю (вместе с некоторыми другими службами) в файле configureServices.ts.
// configureServices.ts
import { createBrowserHistory } from "history";
export const history = createBrowserHistory();
Мой index.ts выглядит так:
import { history } from "./configureServices";
ReactDOM.render(
<Provider {...stores}>
<AppComponent history={history} />
</Provider>,
document.getElementById("root") );
И мой AppComponent, который имеет всемаршруты выглядят так:
import { History } from "history";
import { Route, Switch } from "react-router-dom";
import { Router } from "react-router-dom";
import * as Routes from "../../routes";
...
// Import Components
...
interface Props {
history: History;
...
}
export class AppComponent extends React.Component<Props, {}> {
componentDidMount() {
this.props.authStore && this.props.authStore.authenticate();
}
render() {
return (
<Router history={this.props.history}>
// For toasts, please ignore for this example
<ToastProvider
placement={toastPlacement}
autoDismissTimeout={toastDismissTimeout}
>
// Main App Div = Navbar + Components
<div className="font-sans flex flex-col h-full text-phi-green-munsell bg-phi-gunmetal-rich-dark">
<NavBarComponent />
// This is where the routes are
<div className="container mx-auto p-2 md:p-3 lg:p-4 justify-start">
<Switch>
<Route
exact={true}
path={Routes.homePage}
component={HomepageContainer}
/>
<Route
exact={true}
path={Routes.logOut}
component={LogOutContainer}
/>
<Route
exact={true}
path={Routes.welcome}
component={WelcomeContainer}
/>
<Route
path={Routes.explore}
component={ExploreComponent}
/>
<Route
path={Routes.searchResults}
component={SearchResultsComponent}
/>
</Switch>
</div>
<Footer />
<DevTools position={mobxDevToolsPosition} />
</div>
</ToastProvider>
</Router>
);
}
}
Еще раз спасибо за помощь в этом.