繁体   English   中英

React路由器浏览器后退按钮不起作用

[英]React router browser back button isn't working

我正在尝试使用React JS和react-router创建一个多步骤表单。

表单步骤随状态而变化。 如果我单击下一步按钮,状态步骤将递增,并显示下一步。

但是这样,如果我在第三步,我点击浏览器中的后面,我被重定向到主页而不是上一步。

我的主要组件是这样的:

componentWillMount(){
    console.log(this.props.params.id);
}

onButtonClick(name, event) {
    event.preventDefault();

    switch (name) {
        case "stepFourConfirmation":
            if(this.validation("four")) {
                this.props.actions.userRegistrationThunk(this.state.user);
                this.setState({step: 5, user: {}});
            }
            break;
        case "stepTwoNext":
            if(this.validation("two")) {
                this.setState({step: 3});
                this.context.router.push("stepThree");
            }
            break;
        case "stepThreeFinish":
            this.setState({step: 4});
            break;
        default:
            if(this.validation("one")) {
                this.setState({step: 2});
                this.context.router.push('stepTwo');
            }
    }
}

在每个按钮上单击我将参数推送到URL并更改步骤。 当我点击下一步它的工作完美。 在componentWillMount中,我试图从url获取参数,我会根据参数减少步骤。

但只有当第一步加载时我才会在控制台中执行stepOne。 如果我点击下一步我得到[react-router]位置“stepTwo”与任何路线都不匹配

我的routes.js文件如下:

    import React from 'react';
import {IndexRoute, Route} from 'react-router';

import App from './components/App';
import HomePage from './components/HomePage';
import Registration from './components/registration/RegistrationPage';

import UserPage from './components/user/userHome';
import requireAuth from './common/highOrderComponents/requireAuth';
import hideIfLoggedIn from './common/highOrderComponents/hideIfLoggedIn';

import PasswordReset from './common/passwordReset';

const routes = (
    <Route path="/" component={App}>
        <IndexRoute component={HomePage}/>
        <Route path="registration/:id" component={hideIfLoggedIn(Registration)}/>
        <Route path="reset-password" component={PasswordReset} />
        <Route path="portal" component={requireAuth(UserPage)} />
    </Route>
);

export default routes;

任何建议如何解决?

尝试推动绝对路径。 代替

this.context.router.push("stepTwo");

尝试

this.context.router.push("/registration/stepTwo");

此外,您的生命周期方法也存在问题。 componentWillMount只被调用一次。 当您按下下一个路径时,组件不会再次安装,因此您看不到具有下一个参数的日志。 使用componentWillMount作为初始日志,componentWillReceiveProps用于下一个日志:

componentWillMount() {
  console.log(this.props.params.id);
}

componentWillReceiveProps(nextProps) {
  console.log(nextProps.params.id);
}

顺便说一句:这是关于github讨论 创建者声明,路由器不支持相对路径

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM