【发布时间】:2018-06-12 15:10:18
【问题描述】:
我已经在 react.js 中构建了一个 SPA,我正在使用 react-router-dom、react-redux 和其他一些模块。
我正在使用 react-router-dom 并且我正在使用 switch 组件。
我的路线:
const allRoutes = [
{
path: "/Intro",
name: "Intro",
component: Intro
},
{
path: "/Room",
name: "Room",
component: Room
},
{
path: "/Simulation",
name: "Simulation",
component: Simulation
},
{
path: "/Cartypes",
name: "Cartypes",
component: CarTypes
},
{
path: "/StartPosition",
name: "StartPosition",
component: StartPosition
},
{
path: "/Movment",
name: "Movment",
component: Movment
},
{ redirect: true, path: "/", to: "/Intro", name: "Intro" }
];
export default allRoutes;
我如何渲染它们。
<Switch>
{routes.map((prop, key) => {
if (prop.redirect)
return <Redirect from={prop.path} to={prop.to} key={key} />;
return (
<Route path={prop.path} component={prop.component} key={key} />
);
})}
</Switch>
场景:
在我的一个组件中,我想检测用户何时离开该特定组件,何时更改 url。
为此,我发现我可以在withRouter 的帮助下访问检测 url 更改的侦听器。我把它放在componentWillMount中:
componentWillMount() {
this.unlisten = this.props.history.listen((location, action) => {
console.log("on route change");
console.log(location)
console.log(action)
});
}
一旦用户更改了 url,就会触发这是所期望的……但是。 假设我在“/simulation”,这是我监听任何 url 变化的地方。当我移动到“/room”时,执行了“/simulation”组件中的componentWillMount中的代码,现在我在一个新的url上......
问题:如果我现在从“/room”更改为“/intro”,那么“/simulation”下的componentWillMount 中的相同代码将再次执行。
谁能告诉我为什么?以及如何阻止它执行多次?
【问题讨论】:
标签: javascript reactjs react-router react-redux