在使用 history.push 加载组件后重定向时 - 我的组件会再次呈现。导致 componentDidMount()
函数运行两次。
这是我的一个组件的简化片段。
我希望 componentDidMount()
只运行一次 - 并且它在没有 history.push
的情况下按预期工作。但是当我添加 history.push
- 它会加载两次。 (如果我使用 react-router
中的 Redirect
也会发生同样的情况)
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
很想找到一种只运行一次的方法。
编辑:感谢大家的回复。我将发布一个快速代码片段,然后稍后发布一个 Fiddle。
--- 更新:
我正在使用 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>
);
}
}
再次感谢你帮我解决这个问题。
最佳答案
有几件事可能会导致您的组件重新挂载。
- 如果此组件上方的 React 组件树发生变化。这可能是由于具有多个显示此组件的
Route
组件,但路径从一个更改为另一个。即使最终显示的是同一个组件,但是匹配到的Route
组件发生了变化。 - 如果这个组件的 key 改变了。如果您正在做一些事情,例如使用随机生成的键,或使用数组索引作为键和重新排序元素,那么您将看到组件重新挂载。
关于javascript - React history.push 重新加载组件。希望它只加载一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54426308/