我正在尝试使用 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] Location "stepTwo"did not match any routes
我的 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);
}
顺便说一句:这是一个 discussion on github .创作者声明,React 路由器不支持相对路径
关于javascript - react 路由器浏览器后退按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38138483/