【发布时间】:2016-10-10 05:04:37
【问题描述】:
几个小时前我问了question,一切正常。 但问题是当我在第三步时单击徽标时,我被重定向到第二步而不是主页。
知道如何避免这种情况,当我点击徽标时,无论我在哪一步,它都会将我重定向到主页。
【问题讨论】:
标签: reactjs react-router
几个小时前我问了question,一切正常。 但问题是当我在第三步时单击徽标时,我被重定向到第二步而不是主页。
知道如何避免这种情况,当我点击徽标时,无论我在哪一步,它都会将我重定向到主页。
【问题讨论】:
标签: reactjs react-router
也许您必须验证 nextLocation 是否为 '/' 并返回 true:
componentDidMount = () => {
this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave);
//or this.context.router, depending on your app
}
routerWillLeave = (nextLocation) => {
if(nextLocation === '/') {
return true;
}
if (this.state.step > 1) {
this.setState({step: this.state.step-1});
return false;
}
}
【讨论】:
基本上routerWillLeave 钩子现在总是会在你做一些会导致路由改变的事情时启动。由于您只希望在步骤之间导航时出现这种特殊行为,因此您可以添加某种 flag 变量来确定您是否想要“正常”行为。
试试这个:
routerWillLeave = (nextLocation) => {
if (this.state.step > 1 && this.flag) {
this.setState({step: this.state.step-1});
this.flag = false; // <-- reset the flag.
return false;
}
this.flag = false; // <-- reset the flag.
}
我将&& this.flag 添加到您的代码中,这意味着step 需要大于1 并且flag 需要为true 才能使step减少。
要实际设置标志,请在单击更改step 的按钮时将其设置为true。
onButtonClick(name, event) {
event.preventDefault();
this.flag = true; // <-- We clicked on button; set flag to true
switch (name) {
case "stepFourConfirmation":
this.setState({step: 1});
break;
case "stepTwoNext":
this.setState({step: 3, errors: {}});
break;
case "stepThreeFinish":
this.setState({step: 4});
break;
default:
this.setState({step: 2, errors: {}});
}
}
【讨论】:
routerWillLeave 将执行 if 语句,因为步长大于 1 并且标志为真,它会将我重定向到上一步。
onClick 函数中。我没有你的完整代码。但是这里的解决方案很简单,只需在单击按钮时将flag 设置为true,然后在routerWillLeave 函数中将其重置为false。玩一下,我相信你会找到的:)